pthread_create实例

pthread_create在调用成功后会返回0,否则返回一个非0值,用strerror函数可以看到错误信息。

创建5个缺省线程(即具有缺省属性的线程),打印出线程创建的序号,所在进程的id以及线程id。

main.cpp

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
void* st_routine(void* args){
	pid_t pid = getpid();
	pthread_t thread_id = pthread_self();
	printf("%s process id is %u; thread id is %u\n", (char*)args, (unsigned int)pid, (unsigned int)thread_id);
	return ((void*)0);
}
int main(){
	//sprintf((char*)str, "serial number is %d", 0);
	//printf("%s\n", (char*)str);
	const int n = 5; 
	pthread_t pids[n]; 		
	void* str[n];
	int err;
	for(int i = 0; i < n; i++){
		str[i] = malloc(32);
		sprintf((char*)str[i], "serial number is %d", i);
		if((err = pthread_create(pids+i, NULL, st_routine, str[i])) != 0){
			fprintf(stderr, "fail to create %dth thread, error msg:%s\n", i, strerror(err));	
		}
	}
	//需要让主线成睡眠一下,否则退出太快,pthread_create创建的线程会被
	//极早中断
	sleep(1); 
	return 0; 
}

 在终端执行如下命令即可看到效果。

g++ -pthread -o main main.cpp && ./main

 

一组输出如下:

 

serial number is 4 process id is 13202; thread id is 3042868032
serial number is 3 process id is 13202; thread id is 3051260736
serial number is 2 process id is 13202; thread id is 3059653440
serial number is 1 process id is 13202; thread id is 3068046144
serial number is 0 process id is 13202; thread id is 3076438848
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值