多线程测试
代码(两个线程,一个打印奇数,一个打印偶数)
思路:用c++11的互斥量mutex,条件变量condition_variable.一个全局变量i,控制每个线程获取互斥锁后执行一次,再通过条件变量唤醒另一个等在该锁上的线程,让其执行,即保证两个线程交替运行。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#define CHILD_MESS "Odd:\n"
#define PAR_MESS "Even\n"
#define oops(m,x) { perror(m); exit(x); }
main()
{
int pipefd[2];
int i=0,j=0;
int len;
char buf[BUFSIZ];
int read_len;
if ( pipe( pipefd ) == -1 )
oops("cannot get a pipe", 1);
switch( fork() ){
case -1:
oops("cannot fork", 2);
case 0:
len = strlen(CHILD_MESS);
while(1){
if (write( pipefd[1], CHILD_MESS, len) != len ){
oops("write", 3);
}
for(i;i<10;i++){
srand((unsigned int)time(NULL));
printf("奇数随机数为:%d\n",rand()*2+1);
sleep(1);
}
}
default:
len = strlen( PAR_MESS );
while(1){
if ( write( pipefd[1], PAR_MESS, len)!=len ){
oops("write", 4);
}
for(j;j<10;j++){
srand((unsigned int)time(NULL));
printf("偶数随机数为:%d\n",rand()*2);
sleep(1);
}
read_len = read( pipefd[0], buf, BUFSIZ );
if ( read_len <= 0 )
break;
write( 1 , buf, read_len );
}
}
}
运行结果截图


浙公网安备 33010602011771号