编写多线程程序,主线程中开启两个线程,一个线程打印十个偶数随机数,一个线程打印十个奇数随机数。
#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 );
}
}
}
标签:多线程,int,len,MESS,oops,测试,include
From: https://www.cnblogs.com/20201212ycy/p/16876028.html