使用c的标准库函数创建线程

c 复制代码
#include <stdio.h>
#include <threads.h>
#include <time.h>

int thrd_proc(void * varg){
	 
	// 打印10次
    int times = 10;
	struct timespec ts = {1,0}; // 1秒, 0纳秒
	
	while(times--){
		printf("%s\n",(char *)varg);
		
		// 每隔1秒,打印一次
		thrd_sleep(&ts,0);
	}
}

// 使用c的标准库函数创建线程
int main(void)
{
    thrd_t t1, t2;
	
	printf("hello\n");
	thrd_create(&t1, thrd_proc, "thread 1");
	thrd_create(&t2, thrd_proc, "thread 2");
	
	thrd_join(t1,0);
	thrd_join(t2,0);
	
    return 0;
}

gcc mainthread.c 编译报错。

gcc mainthread.c -lpthread 加上 -lpthread 后,即编译正常.

./a.out 运行程序,正常运行

相关推荐
Wish3D20 分钟前
阿里云OSS 上传文件 Python版本
开发语言·python·阿里云
凤年徐20 分钟前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
oioihoii22 分钟前
C++11 右值引用:从入门到精通
开发语言·c++
朝新_3 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir3 小时前
Calendar类日期设置进位问题
java·开发语言
风逸hhh4 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮5 小时前
Python训练第四十三天
开发语言·python
ascarl20106 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc6 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗6 小时前
Python打卡训练营day46——2025.06.06
开发语言·python