如题所述:

编写程序完成如下功能:

1)有一int型全局变量g_Flag初始值为0;

2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1

3) 在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2

4) 线程序1需要在线程2退出后才能退出

5) 主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>



int g_flag = 0;
pthread_cond_t cond_self_kill;
pthread_mutex_t m_kill;
pthread_mutex_t m_flag;



void *thread_child(void *arg)
{
	if(pthread_mutex_lock(&m_flag)!= 0)
	{
	    pthread_exit(NULL);
	}
    g_flag =(int)arg;
    printf("this is thread%d\n", (int)arg);
	if(pthread_mutex_unlock(&m_flag)!= 0)
	{
	    pthread_exit(NULL);
	}
    if((int)arg == 1)
    {
        if(pthread_cond_wait(&cond_self_kill, &m_kill) != 0)
        {
            pthread_exit(NULL);        
        }
        printf("thread%d exit\n", (int)arg);  
        
    }
    else
    {
        sleep(2);
        pthread_cond_broadcast(&cond_self_kill);
        printf("thread%d exit\n", (int)arg);  

    }
	pthread_exit(NULL);        

}


int main(int argc, char *argv[])
{

	pthread_t child[2];
	int ret;
	pthread_cond_init(&cond_self_kill, NULL);
	pthread_mutex_init(&m_flag, NULL);
	pthread_mutex_init(&m_kill, NULL);
	
	
    ret = pthread_create(&child[1], NULL, thread_child, (void*)2);
	if(ret)
	{
		return 1;
	}	
	ret = pthread_create(&child[0], NULL, thread_child, (void*)1);
	if(ret)
	{
		return 1;
	}	



    if(pthread_join(child[0], NULL) != 0)
    {
        pthread_join(child[1], NULL);
        return 1; 
    }
    pthread_join(child[1], NULL);
    printf("main thread exit\n");
    return 0;
}

 

 

posted on 2014-08-28 20:50  Notflybird  阅读(219)  评论(0编辑  收藏  举报