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;
}