Question

I'm writing a program which reads portions of data in different threads then finds a pattern within them.

But before that (the problem occurs in code below) I just wanted to check whether threads cancel properly. That's where I'm stuck. It takes time to see an error, but basically after (sometimes 40 times) starting my program, it hangs in the while loop in main thread

while (alive_threads) { //never ends, because alive_threads==1, but pthread_cleanup_pop should make sure that all canceling threads reduces counter and as a result reduce it to 0
 usleep(1000);
}

... waiting for the last thread to cancel.

Code is here: http://pastebin.com/VqRrhXPD

I've also supplied content of file I'm reading from.

Opening:

./a.out 20 test.txt 40 clean

20 -number of threads

40 -portion of data
Was it helpful?

Solution

You are modifying the global variable alive_threads without any memory synchronization. This invokes undefined behavior; in all likelihood, it causes some of the decrements to be lost.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top