/*
主线程和子线程之间的保序,
子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#define DEBUG 1
int num = 0;
int times = 0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
void* thread_func2(void *arg)
{
while (times < 50) {
pthread_mutex_lock(&mylock);
//子线程在10~110中等待
while(num >= 10 && num < 110 ){
pthread_cond_wait(&qready, &mylock);
}
printf("%c", 'A');
++num;
pthread_mutex_unlock(&mylock);
pthread_cond_broadcast(&qready);
}
return (void *)0;
}
int main()
{
pthread_t tid;
int work = 0;
void *tret;
pthread_create(&tid, NULL, thread_func2, (void *)&work);
while (times < 50) {
pthread_mutex_lock(&mylock);
//主线程在10内等待
while(num < 10){
pthread_cond_wait(&qready, &mylock);
}
printf("%c", 'B');
num++;
if (num == 110) {
++times;
if (times == 50){
pthread_cancel(tid);
}
num = 0;
}
pthread_mutex_unlock(&mylock);
pthread_cond_broadcast(&qready);
}
pthread_join(tid, &tret);
return 0;
}