Linux 多线程 pthread_create、pthread_join 、pthread_self
线程创建函数:
/* Create a new thread, starting with execution of START-ROUTINE
getting passed ARG. Creation attributed come from ATTR. The new
handle is stored in *NEWTHREAD. */
extern int pthread_create (pthread_t *__restrict __newthread,
const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg) __THROWNL __nonnull ((1, 3));
1. __newthread : pthread_t 变量的地址,用于返回线程标识,也就是线程id。
2.__attr : 线程的属性,可以设置为NULL,即:使用默认属性。
3.__start_routine : 线程入口函数
4.__arg : 线程入口函数的参数
/* Obtain the identifier of the current thread. */
extern pthread_t pthread_self (void) __THROW __attribute__ ((__const__));
线程标识 :获取当前线程的 ID 标识
/* Make calling thread wait for termination of the thread TH. The
exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
is not NULL.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_join (pthread_t __th, void **__thread_return);
线程等待 :等待目标线程执行结束
1.__th :目标线程 id
2. __thread_return : 目标线程的入口哈数的返回值。(也就是线程入口函数的返回值)。在大多数情况下:我们不需要这个返回值,这个返回值 为 NULL。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
void* thread_entry(void* arg)
{
pthread_t id = pthread_self();
int n =(long)arg;
int i=0;
for(i=0;i<n;i++)
{
printf("tid=%ld,i=%d\n",id,i);
sleep(1);
}
return NULL;
}
void func2()
{
pthread_t t1=0;
pthread_t t2=0;
int arg1=5;
int arg2=5;
pthread_create(&t1,NULL,thread_entry,(void*)arg1);
pthread_create(&t2,NULL,thread_entry,(void*)arg2);
printf("t1=%ld\n",t1);
printf("t2=%ld\n",t2);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
printf("child thead is finished...\n");
}
int main()
{
func2();
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)