Linux多线程编程学习代码记录(代码已上传gitee,点个Star也不错哦!)
https://gitee.com/chenshao777/linux_thread.git
【Linux多线程编程-自学记录】
01.线程ID与进程ID
02.创建线程
03.主线程与子线程生命周期
04.线程链接-pthread_join
05.取消线程
06.向线程发送信号-sigaction
07.线程清除
08.Linux多线程互斥量
09.Linux多线程之读写锁
10.条件变量
02.创建线程
笔记:
int pthread_create(pthread_t*restrict thread,
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;
}