There are quite a few mistakes:
First, you’re passing pointer to int random
but in the thread you convert the argument (pointer) to the number. Either you have to cast the int random
to a pointer or in the thread cast args
to long *
and read the memory from that pointer. The latter will actually stop working once you launch several threads as you’ll change the variable content in the meantime or even leave the scope of that variable.
Secondly, you don’t wait for the thread(s). Use pthread_join
to wait for thread.
Third, you run only single thread, you need to create in loop from 0
to nThreads
and once launching all of them, call pthread_join
in similar loop.
Fourth, the size of int
is 4 on most platforms while you send only 2 bytes. This may work on low endian platforms but will fail on big endian. Use sizeof(int)
for both write
and read
to make it more portable.
3
solved Why do threads not work properly?