Results 1 to 2 of 2
Hello Everyone!!
I just started with Pthreads and don't really know much about it. I want to suspend pthreads but apparently, there is no such function as pthread_suspend. I read ...
- 06-29-2010 #1Just Joined!
- Join Date
- Jun 2010
- Posts
- 1
Suspend Pthreads without condition
Hello Everyone!!
I just started with Pthreads and don't really know much about it. I want to suspend pthreads but apparently, there is no such function as pthread_suspend. I read somewhere about suspending pthreads using mutexes and semaphores and used it as following:
#include <pthread.h>
class PThread {
public:
pthread_t myPthread;
pthread_mutex_t m_SuspendMutex;
pthread_cond_t m_ResumeCond;
void start() {
pthread_create(&myPthread, NULL, threadRun, (void*)this );
}
Thread() { }
void suspendMe() {
pthread_cond_wait(&m_ResumeCond,&m_SuspendMutex);
}
void resume() {
pthread_cond_signal(&m_ResumeCond);
}
};
but I don't understand why we need both mutex and condition to suspend and resume a pthread. Is it possible to suspend and resume it without using conditions?
- 06-29-2010 #2
So basically, threads are just like processes and run bits of execution. The question that I would ask is: why is it that you want to suspend your thread?
Mutexes are basically locks: they only allow a single thread to pass at a time. This is used for thread-unsafe code. You may have code that, if two threads were executing at the same time, would give very strange results. Therefore, you can lock this section with a mutex. The first thread to arrive locks the mutex. The second thread tries to lock the mutex, but can't, because it is already locked. Therefore, the second thread must wait for the first thread to unlock the mutex before it can continue. This means that whenever a piece of thread enters a mutex-locked piece of code, it knows that it is the only thread in that code.
Conditions, on the other hand, allow you to wait for a particular something to happen. Conditions are commonly used in mutex-locked code, hence the association of conditions with mutexes.
Basically, a thread does work, and then waits for something else to happen. While it is waiting, it unlocks any mutex that it holds, so that other code can enter mutex-locked areas.
Once somebody signals the condition that the thread is waiting for, the thread will re-obtain its mutex and continue executing.
So depending on why you want to suspend, exactly how to implement it may be different.DISTRO=Arch
Registered Linux User #388732


Reply With Quote