Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I am trying to write a program in C as an exercise to learn multithreading. I have an array of integers, and a thread for each consecutive pair of those integers. Each thread calls an instance of the same function to work on a different pair of integers in the array, via pointers. Obviously there is a mutual exclusion problem here, which I am trying to address with mutexs and condition variables. The algorithm each thread calls locks the mutexs for a given pair of integers, then calls the wait function of the corresponding condition variables. The problem I am facing in this case is, when each thread starts of waiting, what can I do to determine which of them stops waiting and takes the first turn at accessing the array, as I have the signal sent to each condition after access. The program I have does seem to do something, though I don't totally understand why, but the first thread to call the function always freezes on the wait condition, even though other thread move past to the signalling stage.
I hope that makes sense, sorry it goes on so much. Thank you very much for any help

You don't specify your system, and that's unfortunate. Threading models are sadly not platform independent. As my programming experience has centered on Windows, expect my answers to have the same limited bias.
Obviously there is a mutual exclusion problem here
Maybe, maybe not. By your description, it sounds like only one thread will work on a set of numbers. If that's the case, then they're mutually exclusive by default.what can I do to determine which of them stops waiting and takes the first turn at accessing the array, as I have the signal sent to each condition after access.
How does the master thread know? It doesn't (but it does have a reasonable assumption). How do your threads know? They don't. That's why we have mutexes.the first thread to call the function always freezes on the wait condition, even though other thread move past to the signalling stage.
This would be where I'd look at your code, looking for the problem. However, you never included any, so I'm going to show a similar level of effort and pull something randomly from the air: If your PC is multi-core/CPU, your first thread is probably dealing with stale cached data. You need to place a memory barrier before and after the read attempt on your condition variable. Consult your complier's documentation to find out how. (In VS2K5 & VS2K8, you do so by declaring the variable volatile.)

![]() |
shutdown - Returnil - reg...
|
Batch files does not exec...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |