C++新建线程实例

来源:互联网 发布:长时间录制视频软件 编辑:程序博客网 时间:2024/06/05 13:32

 此代码需在linux 系统下运行,windows下不可以,貌似要下个包。具体google.

pthread_create的函数原型为:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,    void *(*start_routine)(void*), void *arg);

pthread_join函数原型为:
int pthread_join(pthread_t thread, void **value_ptr);

#include <pthread.h>

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>

using namespace std;


//mythread名字可以任意起,只要在允许的范围内
void *  mythread(void * ){
while(true){
         printf("===child thread print1\n");
sleep(1);
printf("====child thread print2\n");
}
}
int main(void){
pthread_t t;
int ret;
ret=pthread_create(&t,NULL,mythread,NULL);//此处第三个参数mythread表示传进去的是mythread函数的地址,可以用&mythread,
if(ret!=0){
  printf("create thread failed \n");
exit(1);
}
while(true){
printf("-----main thread is running1 \n");
sleep(1);
printf("-----main thread is running2\n");
}
pthread_join(t,NULL);
return 0;

}


编译gcc test.cpp -pthread -lstdc++

运行 ./a.out 

可以看到主线程和子线程交替打印信息。

关于pthread_join的解释很多都是这么说的:

       “代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。”

通过打印结果看貌似是对的,跟java 线程中的join的效果不一样。java中被join的线程必须运行完了,调用方才接着运行。而这里是可以一起运行的。


0 0