C++新建线程实例

Linux下多线程编程示例
本文介绍了一个简单的Linux下多线程编程示例,使用pthread库创建了一个子线程,并展示了如何让主线程与子线程并行运行及等待子线程结束的方法。

 此代码需在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的线程必须运行完了,调用方才接着运行。而这里是可以一起运行的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值