在进程中的线程通信pthread fork
?
这几天一直被人问,你做过线程和进程吗?
以下写个例子
?
在进程中的线程通信
?
?
#include <stdio.h>#include <stdlib.h>#include <pthread.h>void task1();void task2();int G_INT=0;pthread_mutex_t mlock;pthread_attr_t at1;pthread_attr_t at2;int ret;int main(int argc,char *argv[]){ret=pthread_attr_init(&at1);ret=pthread_attr_init(&at2);ret=pthread_attr_setdetachstate(&at1,PTHREAD_CREATE_DETACHED);ret=pthread_attr_setdetachstate(&at1,PTHREAD_CREATE_JOINABLE);if(fork()==0) { pthread_t t1,t2; ret=pthread_create(&t1,&at1,(void *)task1,NULL); ret=pthread_create(&t2,&at2,(void *)task2,NULL); if(ret) { perror("t2 create:"); exit(EXIT_FAILURE); } pthread_join(t2,NULL); pthread_join(t1,NULL); pthread_attr_destroy(&at1); pthread_attr_destroy(&at2); } return 0;}void task1(){while(1) { ret=pthread_mutex_lock(&mlock); G_INT++; ret=pthread_mutex_unlock(&mlock); if(G_INT>5000) G_INT=0;sleep(1);}}void task2(int *p){while(1) {printf("\nG_INT= %d\n",G_INT); sleep(60);}}