使用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 运行程序,正常运行

相关推荐
落日漫游几秒前
K8s资源管理:高效管控CPU与内存
java·开发语言·kubernetes
PP东19 分钟前
Pyhton基础之多继承、多态
开发语言·python
元直数字电路验证21 分钟前
Jakarta EE课程扩展阅读(二)
开发语言·jakarta ee
滴滴滴嘟嘟嘟.34 分钟前
Qt动画功能学习
开发语言·qt·学习
福大大架构师每日一题1 小时前
go 1.25.1发布:重点修复net/http跨域保护安全漏洞(CVE-2025-47910)
开发语言·http·golang
Ophelia(秃头版1 小时前
经典设计模式:单例模式、工厂模式
java·开发语言·单例模式
Dear.爬虫1 小时前
Golang中逃逸现象, 变量“何时栈?何时堆?”
开发语言·后端·golang
编码浪子2 小时前
趣味学RUST基础篇(构建一个命令行程序2重构)
开发语言·重构·rust
echoarts3 小时前
MATLAB R2025a安装配置及使用教程(超详细保姆级教程)
开发语言·其他·matlab
阿方.9183 小时前
《数据结构全解析:栈(数组实现)》
java·开发语言·数据结构