pthread线程

linux多线程

1. 头文件

  • <pthread.h>

2. 编译

  • gcc -o test test.c -lpthread

3. 变量

  • pthread_t
  • pthread_cond_t
  • pthread_mutex_t

4. 函数

  • pthread_create
  • pthread_join
  • pthread_exit
  • pthread_mutex_lock
  • pthread_mutex_unlock
  • pthread_cond_signal
  • pthread_cond_broadcast
  • pthread_cond_wait
  • pthread_cond_timewait

4.1 pthread_create

int pthread_create(pthread_t *pid, const pthread_attr_t * attr, void*(*func)(void),void*arg)
# 创建新线程
# pid:线程id
# attr:线程属性,一般为空
# func:线程函数
# arg:线程函数参数
# 返回值:0,成功

4.2 pthread_join

int pthread_join(pthread_t pid, void**retval)
# 回收线程资源,父线程阻塞
# pid,线程id
# retval,线程返回值
# 返回值:0,成功

4.3 pthread_exit

void pthread_exit(void *val)
# 终止线程
# val,线程返回值

5. 测试代码

/* file:pthread_test.c
 * gcc -o pthread_test pthread_test.c -lpthread
 */

#include <stdio.h>
#include <pthread.h>

#define log(fmt,...) printf("%s:%d:"fmt"\n",__func__,__LINE__,##__VA_ARGS__)

pthread_cond_t		cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t 	cond_mutex = PTHREAD_MUTEX_INITIALIZER;

void *thread_test1(void *arg)
{
	pthread_mutex_lock(&cond_mutex);
	pthread_cond_wait(&cond,&cond_mutex);
	pthread_mutex_unlock(&cond_mutex);
	log("%s",(char*)arg);

	return NULL;
}

void *thread_test2(void *arg)
{
	pthread_mutex_lock(&cond_mutex);
	pthread_cond_signal(&cond);
	log("%s",(char*)arg);
	pthread_mutex_unlock(&cond_mutex);

	pthread_exit("exit pthread");
	return NULL;
}

int main()
{
	char *buf1="test thread1";
	char *buf2="test thread2";
	void *buf;

	pthread_t thread[2];

	pthread_create(&thread[0], NULL, thread_test1, (void *)buf1);

	pthread_create(&thread[1], NULL, thread_test2, (void *)buf2);

	pthread_join(thread[0],NULL);
	pthread_join(thread[1],&buf);
	
	log("%s",(char *)buf);

	return 0;
}

posted @   roverqqq  阅读(64)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示