C++新建线程实例

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

pthread_create的函数原型为:linux

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>ios

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

using namespace std;c++


//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;

}windows


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

运行 ./a.out google

能够看到主线程和子线程交替打印信息。spa

关于pthread_join的解释不少都是这么说的:线程

       “代码中若是没有pthread_join主线程会很快结束从而使整个进程结束,从而使建立的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束本身才结束,使建立的线程有机会执行。”code

经过打印结果看貌似是对的,跟java 线程中的join的效果不同。java中被join的线程必须运行完了,调用方才接着运行。而这里是能够一块儿运行的。

相关文章
相关标签/搜索