现在的位置: 首页 > 综合 > 正文

线程同步

2018年01月11日 ⁄ 综合 ⁄ 共 1779字 ⁄ 字号 评论关闭

测试程序:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

static pthread_mutex_t mutex;
static pthread_cond_t cond;

static int m_exiting = 0;

static void *proc(void *arg)
{
    int i = 0;
	while(m_exiting != 1 )
	{
		pthread_mutex_lock(&mutex);
        printf("now:%d,proc looping %d\n",time(NULL),i++);
        sleep(1);
		pthread_mutex_unlock(&mutex);
	}

    printf("now:%d,proc will be stop after 10 seconds\n",time(NULL));
    sleep(10);
    pthread_cond_signal(&cond);

    return NULL;
}

void start_foo()
{
	pthread_t tid;
	pthread_create(&tid, NULL, proc, NULL);
}
void stop_foo()
{
    printf("now:%d,requst stop thread\n",time(NULL));
    m_exiting = 1;
    pthread_cond_wait(&cond, &mutex);
    printf("now:%d,stop ok\n",time(NULL));
}
int main()
{
	printf("condition variable study!\n");
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

    start_foo();
    sleep(30);
	stop_foo();
    printf("bye bye\n");
	return 0;
}

运行结果:

condition variable study!
now:1388596343,proc looping 0
now:1388596344,proc looping 1
now:1388596345,proc looping 2
now:1388596346,proc looping 3
now:1388596347,proc looping 4
now:1388596348,proc looping 5
now:1388596349,proc looping 6
now:1388596350,proc looping 7
now:1388596351,proc looping 8
now:1388596352,proc looping 9
now:1388596353,proc looping 10
now:1388596354,proc looping 11
now:1388596355,proc looping 12
now:1388596356,proc looping 13
now:1388596357,proc looping 14
now:1388596358,proc looping 15
now:1388596359,proc looping 16
now:1388596360,proc looping 17
now:1388596361,proc looping 18
now:1388596362,proc looping 19
now:1388596363,proc looping 20
now:1388596364,proc looping 21
now:1388596365,proc looping 22
now:1388596366,proc looping 23
now:1388596367,proc looping 24
now:1388596368,proc looping 25
now:1388596369,proc looping 26
now:1388596370,proc looping 27
now:1388596371,proc looping 28
now:1388596372,proc looping 29
now:1388596373,requst stop thread
now:1388596373,proc will be stop after 10 seconds
now:1388596383,stop ok
bye bye
【上篇】
【下篇】

抱歉!评论已关闭.