Linux多线程编程学习代码(代码已上传gitee,还请各位兄弟点个Star哦!)
https://gitee.com/chenshao777/linux_thread.git
笔记:
int pthread_create(pthread_t*restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg)
第一个参数: 新线程的id,如果成功则新线程的id回填充到tidp指向的内存
第二个参数: 线程属性(调度策略,继承性,分离性…)
第三个参数: 回调函数(新线程要执行的函数)
第四个参数: 回调函数的参数
返回值: 成功返回0,失败则返回错误码
编译时需要连接库pthread
错误码查看
cat /usr/include/asm-generic/errno.h
spu.h文件
#ifndef _SPU_H_
#define _SPU_H_
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#endif
02.create_pthread.c文件
#include "spu.h"
void print_id(char *str)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid = %u, tid = 0x%x\n", str, pid, tid);
}
void *thread_fun(void *arg)
{
print_id(arg);
//return (void*)0;
}
int main()
{
int err;
pthread_t thread_id;
err = pthread_create(&thread_id, NULL, thread_fun, "new thread");
if(err != 0)
printf("create fail, err = %d\n",err);
else
printf("create success!\n");
sleep(1);
print_id("main_id: ");
return 0;
}