您的位置:首页 > 运维架构 > Linux

linux线程的挂起和唤醒

2017-09-05 15:49 225 查看
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

pthread_t IDA;
pthread_t IDB;

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

#define RUN 1
#define STOP 0

int status = RUN;

void * thread_function(void *param)
{
static int i = 0;
while (1)
{
pthread_mutex_lock(&mut);
while (!status)
{
pthread_cond_wait(&cond, &mut);
}
pthread_mutex_unlock(&mut);

//do actual something
printf("thread is running...\n");
sleep(1);
}
}

void thread_resume()
{
if (status == STOP)
{
pthread_mutex_lock(&mut);
status = RUN;
pthread_cond_signal(&cond);
printf("pthread run!\n");
pthread_mutex_unlock(&mut);
}
}

void thread_pause()
{
if (status == RUN)
{
pthread_mutex_lock(&mut);
status = STOP;
printf("thread stop!\n");
pthread_mutex_unlock(&mut);
}
}

void *test(void *param)
{
while(1)
{
sleep(5);
thread_pause();
sleep(10);
thread_resume();
sleep(5);
}
}

int main(int argc, char *argv[])
{
pthread_create(&IDA, NULL, test, NULL);
pthread_create(&IDB, NULL, thread_function, NULL);

pthread_join(IDA, NULL);
pthread_join(IDB, NULL);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息