Pause a thread from an other?

Dec 5, 2011 at 6:37pm
Is it possible to make one thread pause an other in a simple way?
For an example lets say I have 2 threads created and started from int main().
Thread1 has to be paused from Thread2 because they both checks the cin in a dos-alike environment by C++. I would like to enter a command in cin and thereby make Thread2 pause the process of Thread1 so that it doesn´t disturb Thread2 for a funktion and then restart Thread1 from where it was before (not restart from the beginning) when Thread2 is done with its funktion.

I am using Dev C++ 4.9.9.2 and Windows XP for my project by the way!

If it is that easy, it would speed up my text-based game Im working on!

Thanks in advance!
Dec 5, 2011 at 6:41pm
I think you will have to use a mutex or some other synchronisation mechanism.
Dec 5, 2011 at 6:48pm
Multiple threads in a text based game? Sounds like you're doing something very, very wrong.
Last edited on Dec 5, 2011 at 6:48pm
Dec 5, 2011 at 7:36pm
SuspendThread()
ResumeThread()
Play with it if you want.
Dec 5, 2011 at 8:25pm
How does SuspendThread() and ResumeThread() work exactly?
Dec 5, 2011 at 8:53pm
SuspendThread instructs Windows to put a thread to sleep. And ResumeThread to wake it back up.

But it is not what you need here, going by your description. What you need is a critical section. These are a kind of lightweight mutex, which can only be used by threads in the same process. But they are quicker, and cheaper on system resources, so you only use a proper mutex when you need to synchronize with threads in another process.

You use InitializeCriticalSection to prepare your critsect for use. Then you call EnterCriticalSection to enter it, and LeaveCriticalSection to leave it. And DeleteCriticalSection when you're done with it.

Only one thread can enter a critical section at a time. If a thread is in a ciritical section, all other threads which call EnterCriticalSection on the same critsect will be blocked until LeaveCriticalSection is called by the owning thread. For this reason, you should only protect small (and quick) regions of code using this mechanism.

1
2
3
4
5
6
7
8
9
10
11
12
13
CRITICAL_SECTION critsect;
InitializeCriticalSection(&critsect);

...

EnterCriticalSection(&critsect);
cout << "Next command?" << endl;
cin >> cmd;
LeaveCriticalSection(&critsect);

...

DeleteCriticalSection(&critsect);


See MSDN for details

Andy
Last edited on Dec 5, 2011 at 9:02pm
Dec 5, 2011 at 9:44pm
I solved it in an other way, but thanks for the good learning!
Topic archived. No new replies allowed.