网站建设的公司黄页推广平台有哪些
问题:编写程序完成如下功能:程序创建2个线程,然后:
1> 主线程先打印“I am main thread”,然后睡眠2秒后,打印"main thread wake up",主线程退出
2> 第一个新线程先打印“I am the first new thread”,然后睡眠3秒后,打印"the first new thread wake up",退出
3> 第二个新线程先打印“I am the second new thread”,然后睡眠5秒后,打印"the fsecond new thread wake up",退出
要求能看到所有打印信息
代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>void *fun1(){printf("I am the first new thread\n");sleep(3);printf("the first new thread wake up\n");return NULL;
}void *fun2(){printf("I am the second new thread\n");sleep(5);printf("the second new thread wake up\n");return NULL;
}int main(int argc,char *argv[]){pthread_t id[2];int ret = 0;ret = pthread_create(&id[0],NULL,fun1,NULL); // thread1ret += pthread_create(&id[1],NULL,fun2,NULL); // thread2if(ret){printf("pthread_create failed\n");return 1;}printf("I am main thread\n"); // main threadsleep(2);printf("main thread wake up\n");pthread_exit(NULL); // main thread exitpthread_join(id[0],NULL); // thread1 exitpthread_join(id[1],NULL); // thread2 exitreturn 0;
}
输出: