seteuid0's blog
Themed by Diary.
Linux下线程pthread实现suspend、resume的一种方式

Linux下线程pthread没有实现suspend,resume的相关功能,这几天项目需要,自己就使用pthread_cond_wait实现了下,把主要代码逻辑如下,贴出来供大家参考。 功能如下。 主线程监听用户消息,子线程完成实际任务。主线程需要依据用户输入控制工作子线程的暂停(suspend)和继续运行(resume)。 使用CTRL+C控制暂停、继续运行。 使用CTRL+\使程序退出,主线程先cancel,然后自己退出。 代码如下:

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdio.h>

typedef enum \_RUN\_STATUS{
STATUS\_RUNNING = 0,
STATUS\_PAUSE,
}RUN\_STATUS;

sigset\_t mask;

RUN\_STATUS run\_status;

pthread\_mutex\_t lock = PTHREAD\_MUTEX\_INITIALIZER;
pthread\_cond\_t waitloc = PTHREAD\_COND\_INITIALIZER;

void cleanup\_handler(void\*arg)
{
printf("child thread cleanup\\n");
pthread\_mutex\_unlock(&lock);
}

void \* thread\_func(void\*arg)
{

int err, signo;
pthread\_cleanup\_push(cleanup\_handler, NULL);

for(;;){
pthread\_mutex\_lock(&lock);
if(run\_status == STATUS\_RUNNING){
pthread\_mutex\_unlock(&lock);
printf("child pthread task running->>>>>>>>>>>\\n");
sleep(1);

}else{
while(run\_status != STATUS\_RUNNING){
pthread\_cond\_wait(&waitloc, &lock);
printf("running again\\n");
}
pthread\_mutex\_unlock(&lock);
}
}
pthread\_cleanup\_pop(0);
return 0;
}

int main()
{
int ret;
run\_status = STATUS\_RUNNING;

sigset\_t oldmask;
pthread\_t tid;
int err, signo;

sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);

pthread\_t tid\_self = pthread\_self();

if((ret = pthread\_sigmask(SIG\_BLOCK, &mask, &oldmask)) != 0)
perror("SIG\_BLOCK error");
ret = pthread\_create(&tid, NULL, thread\_func, 0);
if(ret != 0)
perror("create thread");

sleep(3);
for(;;){
err = sigwait(&mask, &signo);
if(err!=0)
perror("sigwait failed");

switch(signo){
case SIGINT:
pthread\_mutex\_lock(&lock);
if(run\_status == STATUS\_RUNNING){
run\_status = STATUS\_PAUSE;
printf("\[Pause\]\\n");
}else{
run\_status = STATUS\_RUNNING;
printf("\[Resume\]\\n");
}
pthread\_cond\_signal(&waitloc);
pthread\_mutex\_unlock(&lock);
break;
case SIGQUIT:
printf("kill child thread.\\n");
sleep(1);
pthread\_cancel(tid);
pthread\_join(tid,NULL);
printf("exiting\\n");
return 0;
default:
printf("unexpected signal %d\\n", signo);
return 1;
}

}

return 0;
}

关键字:pthread,thread,linux,pause,suspend,resume,线程,暂停,线程暂停,