Skip to content
Advertisement

pthread mutex does not work correctly on macOS

Currently I am learning POSIX threads on Linux. The following example is counting how many 3(int) there are in an integer array, which returns a correct answer on CentOS 6.5 but a wrong one on macOS 10.12.4.

JavaScript

The answer should be 64 * 1024 * 1024 / 2 = 67,108,864 / 2 = 33,554,432. But the answer on macOS is never right. I compile the code with the following options:

JavaScript

I have tried solving the problem following this link. However, I still got a wrong answer having initialized pthread mutex. Did I miss something?

PS: I have tried either pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; or pthread_mutex_init( &mutex, NULL) but the program running on macOS still returns a wrong answer.

Advanced thanks!

Advertisement

Answer

The line count = 0; before the pthread_create sets count to 0, so you reset the value of count while the threads increment them. Remove this line. It probably worked on other systems, when the main thread finishes the pthread_create before the threads starts counting.

I already mentioned it in the comments:

JavaScript

should be

JavaScript

otherwise you will not wait for the first thread to be done.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement