线程创建
1,代码
项目名:pthread_create.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
/*
getpid 获取进程ID
pthread_self 获取线程ID
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *)
void *arg);
第一个参数: 新线程ID, 创建成功系统回填
第二个参数: 新线程到属性, NULL为默认属性
第三个参数: 新线程到启动函数
第四个参数: 传递给新线程
*/
void print_id(char *s){
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid is %lu, tid is %lx\n", s, pid,tid);
}
void *thread_func(void *arg){
print_id(arg);
return NULL;
}
int main(){
pthread_t ntid;
int err;
err = pthread_create(&ntid, NULL,(void *)thread_func, "new thread");
if(err!=0){ //创建成功返回0
printf("create new thread is failed\n");
return 0;
}
print_id("main thread: ");
sleep(2);
return 0;
}
2, 编译
gcc pthread_create.c -lpthread -o pthread_create
# 因为pthread库不是Linux系统默认的库, 所以编译时要连接连接库, 即加上 -lpthread
3, 执行
./pthread_create
4,结果
main thread: pid is 58861, tid is 7ff2d9767740
new thread pid is 58861, tid is 7ff2d8f46700
5,总结
懵~~~