![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Expert Programmer
Join Date: Aug 2005
Location: Rotterdam, the Netherlands
Posts: 942
Rep Power: 4
![]() |
Locking a thread
Hi,
I'm currently working on a program with multiple threads. All of the threads print to the screen, so the problem is that the messages are often mixed. Creating the function to print into this way: int lock = 0;
void blah() {
while(lock != 0);
lock++;
// code here
lock--;
}wouldn't work: when two threads are pending they will 50% of the time print at the same time. My question is: what is the best way to make sure the messages won't be mixed? I was thinking of locking the thread in a safe way - but what is a safe way? TIA, Poly. |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
Join Date: Oct 2005
Posts: 211
Rep Power: 3
![]() |
I'm a big fan of mutexes
Simple, easy to use, OS level implementation. (note: this might not be the best library, it's just what came in first in google for C++ mutex) -MBirchmeier |
|
|
|
|
|
#3 |
|
Newbie
Join Date: Sep 2005
Posts: 28
Rep Power: 0
![]() |
Take a look at semaphores as well. It's a way to handle data control in multithreaded programs.
I don't know if you can use it in C++ but C has a data type that, access to it is atomic. It is defined by : sig_atomic_t varname; If you are interested in the whole concept of multithreading and synchronizing processes, I know that the book of Tannenbaum about Operating Systems has some notes and algorithms which may help... More info on sig_atomic_t can be found here.
__________________
The geeks shall inherit the earth. |
|
|
|
|
|
#4 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Note that many things (such as signals) are not portable between OSes. Polyphemus may or not may be interested, but his user info indicates that he uses Win and Linux.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#5 | ||
|
Expert Programmer
Join Date: Aug 2005
Location: Rotterdam, the Netherlands
Posts: 942
Rep Power: 4
![]() |
Quote:
.Thanks guys, I'll check them out. Quote:
. |
||
|
|
|
|
|
#6 |
|
Newbie
Join Date: Jan 2006
Posts: 13
Rep Power: 0
![]() |
Maybe what you're looking for are conditional variables. POSIX threads include this so it's postable as far as systems that are POSIX complaints.
You might want too look at: http://users.actcom.co.il/~choo/lupg...thread_condvar Maybe even read the whole article . This is what I used when I first started learning threads. |
|
|
|
|
|
#7 | ||
|
Hobbyist Programmer
Join Date: Oct 2005
Posts: 134
Rep Power: 3
![]() |
Quote:
Quote:
|
||
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|