/* another codes to do sth. in this thread */ /* ** waiting for the exit action of another thread */ pthread_join(thread,NULL); cout<<"the second thread has finished"<<endl; pthread_exit(NULL); }
int main() { pthread_t thread; int i = 10; cout<<"in main process"<<endl; pthread_create(&thread,NULL,threadFunc,(void*)&i); pthread_join(thread,NULL); cout<<"the thread has finished"<<endl; return 0; }
其运行输出为: in main process the cnt is:0 the cnt is:1 the cnt is:2 the cnt is:3 the cnt is:4 the cnt is:5 the cnt is:6 the cnt is:7 the cnt is:8 the cnt is:9 the second thread has finished the thread has finished
发布评论
评论(4)
我认为是可行的
随便做了个测试的小程序:
#include <pthread.h>;
#include <sys/types.h>;
#include <unistd.h>;
#include <iostream.h>;
#include <stdlib.h>;
#include <wait.h>;
void* anotherThreadFunc(void*j)
{
int*k = (int*)j;
for(int i=0;i<*k;i++)
{
cout<<"the cnt is:"<<i<<endl;
}
pthread_exit(NULL);
}
void* threadFunc(void* k)
{
pthread_t thread;
if(pthread_create(&thread,NULL,anotherThreadFunc,k)!=0) //error
{
cerr<<"create thread error"<<endl;
exit(-1);
}
/* another codes to do sth. in this thread */
/*
** waiting for the exit action of another thread
*/
pthread_join(thread,NULL);
cout<<"the second thread has finished"<<endl;
pthread_exit(NULL);
}
int main()
{
pthread_t thread;
int i = 10;
cout<<"in main process"<<endl;
pthread_create(&thread,NULL,threadFunc,(void*)&i);
pthread_join(thread,NULL);
cout<<"the thread has finished"<<endl;
return 0;
}
其运行输出为:
in main process
the cnt is:0
the cnt is:1
the cnt is:2
the cnt is:3
the cnt is:4
the cnt is:5
the cnt is:6
the cnt is:7
the cnt is:8
the cnt is:9
the second thread has finished
the thread has finished
如果要在各个线程进行通讯的话,可以在进程地址空间里划分一些空间出来存放
共享数据就可以了。
以上是个人之见,刚学不久。
非常感谢!
用JAVA很简单!
可是我用的是C呢