主线程和子线程分别循环一定次数

运用到了互斥量和条件变量,分别在主进程和子进程中循环。


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


编译的时候遇到两个问题:

1.C语言中不支持bool类型,所以需要自定义bool为int

2.for语言中,不支持for(int i=..),不然会报一个'for' loop initial declarations are only allowed in C99 mode错误。


#include 
#include 
#include 
#include 
#define bool int
#define true 1
#define false 0

pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int i = 0;
int main_count=0;
int subtread_count=0;
bool main_thread_wait_flag = false;//线程等待标志
bool subthread_wait_flag = false;


void main_thread_func()
{
	while(true)
	{
		pthread_mutex_lock(&mylock);
		main_thread_wait_flag =  true;
		pthread_cond_wait(&cond,&mylock);
		main_thread_wait_flag = false;
		pthread_mutex_unlock(&mylock);

		for(i=1;i<=100;i++)
		{
			printf("main thread: %d\n",i);
		}

		while(true)
		{
			pthread_mutex_lock(&mylock);
			if(true == subthread_wait_flag)
			{
				pthread_cond_signal(&cond);
				pthread_mutex_unlock(&mylock);
				break;
			}
			pthread_mutex_unlock(&mylock);
		}

		++main_count;
		if(main_count >= 50)
		{
			printf("main thread loop over 50 times\n");
			break;
		}

	}
}

void *subthread_func(void *arg)
{
	while(true)
	{
		for(i=1;i<=10;i++)
		{
			printf("subthread: %d\n",i);
		}

		while(true)
		{
			pthread_mutex_lock(&mylock);
			if(true == main_thread_wait_flag)
			{
				pthread_cond_signal(&cond);
				pthread_mutex_unlock(&mylock);
				break;
			}
			pthread_mutex_unlock(&mylock);
		}
		
		pthread_mutex_lock(&mylock);
		subthread_wait_flag = true;
		pthread_cond_wait(&cond,&mylock);
		subthread_wait_flag = false;
		pthread_mutex_unlock(&mylock);

		++subtread_count;
		if(subtread_count >= 50)
		{
			printf("subthread loop over 50 times\n");
			break;
		}
	}
	return (void *)0;
}

int main()
{
	pthread_t tid;

	pthread_create(&tid,NULL,subthread_func,NULL);
	main_thread_func();
	pthread_join(tid,NULL);

	return 0;
}


你可能感兴趣的:(Linux/Shell)