Question

I'm writing a multithreaded program to run a modified bubble sort for a class project. Basically, each thread bubble sorts a segment of an array of integers, and each segment shares one element with its neighboring segments in order for values to flow between them. Currently, I am using pthread_mutex_ts around critical sections; but I must have something wrong, because sometimes it finishes sorted, sometimes it finishes not sorted, and sometimes the program just hangs.

Here's my problem: If I use printf()s to see where I am in each thread, it's virtually guaranteed to not hang (which makes it difficult to figure out where it's getting hung up). So why does using printf()s in certain sections of code run by each thread seem to prevent hanging and cause the program to finish?

Edit: I determined that the main cause of my issue was that I had not properly initialized my mutexes (with pthread_mutex_init()). So chrk was correct that I was using improper synchronization, and the printf() usage slowed things down enough to make it look like some things were working.

Was it helpful?

Solution

I can't be sure about this, obviously, just saying my guess:

Theoritically, printf(3) uses the system call write(2) to stdout, which is a I/O procedure, thus is slower than rest parts of your code which are CPU calculations. So if you have some other synchronization problem, the time spent for printf() to execute could possibly by accident "fix" some instances of that problem.

However that's not a proper way to fix synchronization problems, so you have to check your code again to find the race conditions that are being resolved in a wrong way.

OTHER TIPS

Long ago, I had a similar kind of problem. Hope it helps. I too had printk issues and I found out that complier was optimizing my code and converting my loop to while(1);.

Strange behavior of printk in linux kernel module

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