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