Pthread

来自通通笔记

上课新发现

上实训课老师给讲了个能创建多线程的库。

老师的示例代码是这么写的:

#include <pthread.h>
#include <stdio.h>
/*
	写代码模拟孙悟空变出小猴子,同时处理多个不同的任务
*/
void *fun1(void *arg)
{
	while(1)
	{
		printf("线程1(猴子1)去打哪吒!\n");
		sleep(1);
	}
}

void *fun2(void *arg)
{
	while(1)
	{
		printf("线程2(猴子2)去打托塔李天王!\n");
		sleep(1);
	}
}
int main()
{
	pthread_t id1,id2;
	//创建第一个线程--》打哪吒
	pthread_create(&id1,NULL,fun1,NULL);
	//创建第二个线程--》打托塔李天王
	pthread_create(&id2,NULL,fun2,NULL);
	
	//孙悟空自己打如来佛
	while(1)
	{
		printf("我自己去打如来佛!\n");
		sleep(1);
	}
}

(这个孙悟空比喻有被笑到😂

可以参考的资料

完整的定义

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*) void *arg);

参考资料

在Linux中使用线程_飞芃在路上-CSDN博客_linux thread

pthreads(7) - Linux manual page (man7.org)