请教如何用pthread库实现线程的启动和暂停?
我在linux上,想用pthread库实现这样的功能:我有2个线程:一个主线程,一个工作线程,在主线程中创建工作线程。工作线程不总是工作,也就是说,创建的时候处于暂停状态或休眠状态(不占cpu),当主线程通知它工作的时候就开始工作。开始工作之后,当主线程需要暂停它的时候可以通知它使它暂停。然后工作线程又处于暂停状态(不占cpu)。之后类似,主线程可以随时通知工作线程开始工作,随时暂停工作线程。
我开始的想法是这样的:
pthread_t thread;
int enable = 0;
void* threadFunc(void* args) //工作线程函数
{
while(1)
{
if(enable)
{
work();
}
else
{
sleep(1);
}
}
return ((void*)0);
}
int main()
{
pthread_create(&thread, NULL, threadFunc, NULL);
enable = 1;
sleep(3);
enable = 0;
...
}
pthread_mutex_lock(&mutex));
pthread_cond_wait(&cond,&mutex);
pthread_cond_signal(&cond);
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex_pause = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_pause = PTHREAD_COND_INITIALIZER;
bool pthread_pause = false;
void pthread_suspend(void)
{
if (pthread_pause == false)
{
pthread_mutex_lock( &mutex_pause );
pthread_pause = true;
printf("------pthread pause------/n");
pthread_mutex_unlock( &mutex_pause );
}
else
{
printf("pthread suspend already/n");
}
}
void pthread_resume(void)
{
if (pthread_pause == true)
{
pthread_mutex_lock(&mutex_pause);
pthread_pause = false;
pthread_cond_broadcast(&cond_pause);
printf("------pthread resume------/n");
pthread_mutex_unlock(&mutex_pause);
}
else
{
printf("pthread resume already/n");
}
}
void pthread_pause_location(void)
{
pthread_mutex_lock(&mutex_pause);
while(pthread_pause)
{
pthread_cond_wait(&cond_pause, &mutex_pause);
}
pthread_mutex_unlock(&mutex_pause);
}
}
else
{
printf("pthread resume already/n");
}
}
void* threadFunc(void* args) //工作线程函数
{
while(1)
{
if(pthread_pause == false)
{ work();
}
else
{
pthread_cond_wait(&cond);
}
}
return ((void*)0);
}
int main()
{
pthread_create(&thread, NULL, threadFunc, NULL);
pthread_resume();
pthread_cond_signal(&cond);
sleep(3);
pthread_suspend();
...
}
[解决办法]
void* threadFunc(void* args) //工作线程函数
{
while(1)
{
if(!pthread_pause)
{
printf("working...");
//work();
}
else
{
printf("rest...");
}
sleep(1);
}
return ((void*)0);
}
pthread_t thread;
int main()
{
pthread_create(&thread, NULL, threadFunc, NULL);
while (1){
int c = getchar();
if (c=='s') pthread_suspend();
if (c=='r') pthread_resume();
//if (c=='c') pthread_pause_location();
}
return 0;
}