您的位置:首页 > 编程语言

子线程循环 3 次,接着主线程循环 6 次,接着又回到子线程循环 3 次,接着再回到主线程又循环6 次,如此循环50次,试写出代码。

2016-12-09 16:02 302 查看
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co.,     Ltd.
File name:
Author:Jerey_Jobs    Version:0.1    Date:
Description:
Funcion List:
*****************************************************/

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

int flag = 1;
int n = 0;
pthread_mutex_t mutex;

void fun_thread(char *msg);

int main()
{
pthread_t thread;
int val;
int i;

if(pthread_mutex_init(&mutex,NULL) != 0)
{
printf("init mutex error\n");
exit(1);
}

if(pthread_create(&thread,NULL,(void *)fun_thread,NULL) != 0)
{
printf("create thread error\n");
exit(1);
}

while(1)
{
if(flag == 0)
{
val = pthread_mutex_lock(&mutex);

if(val != 0)
{
printf("main thread lock error\n");
exit(1);
}

printf("main thread has locked\n");

for(i = 0;i < 6;i++)
{
printf("main thread is working    %d times\n",i);
}

flag = 1;

printf("main thread unocked\n");
pthread_mutex_unlock(&mutex);
}
/*  if(n == 5)
exit(1);*/
if(n == 5)
break;
}

return 0;
}

void fun_thread(char *msg)
{
int val;
int i;

while(n < 5)
{
if(flag == 1)
{
val = pthread_mutex_lock(&mutex);

if(val != 0)
{
printf("thread lock error\n");
exit(1);
}

printf("thread has locked\n");

for(i = 0;i < 3;i++)
{
printf("thread is working   %d times\n",i);
}

flag = 0;

printf("thread is unlocked\n");

n++;

printf("*****************************************%d\n",n);
pthread_mutex_unlock(&mutex);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐