Linux系统编程_线程:线程、互斥量、条件变量

1. 线程概述(与进程的区别及线程的优势)(437.1)

进程与线程

  • 典型的 UNIX/Linux 进程可以看成只有一个控制线程:一个进程在同一时刻只做一件事情。有了多个控制线程后,在程序设计时可以把进程设计成在同一时刻做不止一件事,每个线程各自处理独立的任务。

  • 进程是程序执行时的一个实例,是担当分配系统资源(CPU 时间、内存等)的基本单位。在面向线程设计的系统中,进程本身不是基本运行单位,而是线程的容器。程序本身只是指令、数据及其组织形式的描述,进程才是程序(那些指令和数据)的真正运行实例。

  • 线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。线程包含了表示进程内执行环境必须的信息,其中包括进程中表示线程的线程 ID、一组寄存器值、栈、调度优先级和策略、信号屏蔽字、errno 常量以及线程私有数据。进程的所有信息对该进程的所有线程都是共享的,包括可执行的程序文本、程序的全局内存和堆内存、栈以及文件描述符。在 Unix 和类 Unix 操作系统中线程也被称为轻量级进程(lightweight processes),但轻量级进程更多指的是内核线程(kernel thread),而把用户线程(user thread)称为线程。

“进程——资源分配的最小单位,线程——程序执行的最小单位”

  • 进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程没有单独的地址空间,一个线程死掉就等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。但对于一些要求同时进行并且又要共享某些变量的并发操作,只能用线程,(不能用进程。)

使用线程的理由

  • 从上面我们知道了进程与线程的区别,其实这些区别也就是我们使用线程的理由。总的来说就是:进程有独立的地址空间,线程没有单独的地址空间(同一进程内的线程共享进程的地址空间)。

  • 使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。我们知道,在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。

  • 使用多线程的理由之二是线程间方便的通信机制。对不同进程来说,它们具有独立的数据空间,要进行数据的传递只能通过通信的方式进行(信号量、共享内存、消息队列…),这种方式不仅费时,而且很不方便。线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便。当然,数据的共享也带来其他一些问题(条件变量和互斥锁可解决),有的变量不能同时被两个线程所修改,有的子程序中声明为static的数据更有可能给多线程程序带来灾难性的打击,这些正是编写多线程程序时最需要注意的地方。

2. 线程创建等待及退出(438.2)

Linux上线程开发API概要

多线程开发在 Linux 平台上已经有成熟的 pthread 库支持。其涉及的多线程开发的最基本概念主要包含三点:线程,互斥锁,条件。其中,线程操作又分线程的创建,退出,等待 3 种。互斥锁则包括 4 种操作,分别是创建,销毁,加锁和解锁。条件操作有 5 种操作:创建,销毁,触发,广播和等待。其他的一些线程扩展概念,如信号灯等,都可以通过上面的三个基本元素的基本操作封装出来。详细请见下表:
在这里插入图片描述

与线程自身相关API

  1. 线程创建
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
  • 当 pthread_create 成功返回时,由 tidp 指向的内存单元被设置为新创建线程的线程 ID。attr 参数用于定制各种不同的线程属性,暂可以把它设置为 NULL,以创建默认属性的线程。
  • 新创建的线程从 start_rtn 函数的地址开始运行,该函数只有一个无类型指针参数 arg。如果需要向 start_rtn 函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为 arg 参数传入。
  1. 线程退出
  • 单个线程可以通过以下三种方式退出,在不终止整个进程的情况下停止它的控制流:
    • 1)线程只是从启动例程中返回,返回值是线程的退出码。
    • 2)线程可以被同一进程中的其他线程取消。
    • 3)线程调用 pthread_exit:
#include <pthread.h>
int pthread_exit(void *rval_ptr);
  • rval_ptr 是一个无类型指针,与传给启动例程的单个参数类似。进程中的其他线程可以通过调用 pthread_join 函数访问到这个指针。
  1. 线程等待
#include <pthread.h>
int pthread_join(pthread_t thread, void **rval_ptr);
// 返回:若成功返回0,否则返回错误编号
  • 调用这个函数的线程将一直阻塞,直到指定的线程调用 pthread_exit、从启动例程中返回或者被取消。如果例程只是从它的启动例程返回 i,rval_ptr 将包含返回码。如果线程被取消,由 rval_ptr 指定的内存单元就置为 PTHREAD_CANCELED。
  • 可以通过调用 pthread_join 自动把线程置于分离状态,这样资源就可以恢复。如果线程已经处于分离状态,pthread_join 调用就会失败,返回 EINVAL。
  • 如果对线程的返回值不感兴趣,可以把 rval_ptr 置为 NULL。在这种情况下,调用pthread_join函数将等待指定的线程终止,但并不获得线程的终止状态。
  1. 线程脱离
  • 一个线程或者是可汇合(joinable,默认值),或者是脱离的(detached)。当一个可汇合的线程终止时,它的线程 ID 和退出状态将留存到另一个线程对它调用 pthread_join。脱离的线程却像守护进程,当它们终止时,所有相关的资源都被释放,我们不能等待它们终止。如果一个线程需要知道另一线程什么时候终止,那就最好保持第二个线程的可汇合状态。
  • pthread_detach 函数把指定的线程转变为脱离状态。
#include <pthread.h>
int pthread_detach(pthread_t thread);
// 返回:若成功返回0,否则返回错误编号
  • 本函数通常由想让自己脱离的线程使用,就如以下语句:
pthread_detach(pthread_self());
  1. 线程 ID 获取及比较
#include <pthread.h>
pthread_t pthread_self(void);
// 返回:调用线程的ID
  • 对于线程ID比较,为了可移植操作,我们不能简单地把线程ID当作整数来处理,因为不同系统对线程ID的定义可能不一样。我们应该要用下边的函数:
#include <pthread.h>
int pthread_equal(pthread_t tid1, pthread_t tid2);
// 返回:若相等则返回非0值,否则返回0
  • 对于多线程程序来说,我们往往需要对这些多线程进行同步。同步(synchronization)是指在一定的时间内只允许某一个线程访问某个资源。而在此时间内,不允许其它的线程访问该资源。我们可以通过互斥锁(mutex),条件变量(condition variable)和读写锁(reader-writer lock)来同步资源。在这里,我们暂不介绍读写锁。
  • THREAD/demo1.c
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void *func1(void *arg)
{//子线程
	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");//主线程
	}

	printf("main:%ld\n",(unsigned long)pthread_self());//获取线程的ID

	pthread_join(t1,NULL);//如果没有while(1)或join函数,子线程运行可能会丢失

	return 0;
}
  • THREAD/demo2.c
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void *func1(void *arg)
{//子线程
	static int ret = 10;//必须使用静态变量 其在每次函数调用之间保留其值,可在多个函数调用之间共享状态

	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));

	pthread_exit((void *)&ret);//退出
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;

	int *pret = NULL;

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");//主线程
	}

	printf("main:%ld\n",(unsigned long)pthread_self());

	pthread_join(t1,(void **)&pret);//等待,线程将一直阻塞直到退出(ret)

	printf("main: t1 quit: %d\n",*pret);//取内容

	return 0;
}
  • THREAD/demo3.c
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void *func1(void *arg)
{
	static char *p = "t1 is run out";

	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));

	pthread_exit((void *)p);
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;

	char *pret;

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");
	}

	printf("main:%ld\n",(unsigned long)pthread_self());

	pthread_join(t1,(void **)&pret);

	printf("main: t1 quit: %s\n",pret);

	return 0;
}

3. 线程共享内存空间的代码验证(439.3)

  • THREAD/demo4.c(g_data 会连续的++)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
int g_data = 0;

void *func1(void *arg)
{//子线程1
	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));
	while(1){
		printf("t1: %d\n",g_data++);	
		sleep(1);
		if(g_data == 3){//不一定每次都会到他
			pthread_exit(NULL);
		}
	}
}
void *func2(void *arg)
{//子线程2
	printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*((int *)arg));
	while(1){
		printf("t2: %d\n",g_data++);	
		sleep(1);
	}
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");
	}
	ret = pthread_create(&t2, NULL, func2,(void *)&param);
	if(ret == 0){
		printf("main:create t2 success\n");
	}
	printf("main:%ld\n",(unsigned long)pthread_self());//主线程
	while(1){
		printf("main: %d\n",g_data++);	
		sleep(1);
	}

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);

	return 0;
}

4. 线程同步之互斥量加锁解锁(440.4)

与互斥锁相关API

  • 互斥量(mutex)从本质上来说是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。(除man函数主进程 可能会插入其中的子进程中运行)如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。
  • 在设计时需要规定所有的线程必须遵守相同的数据访问规则。只有这样,互斥机制才能正常工作。操作系统并不会做数据访问的串行化。如果允许其中的某个线程在没有得到锁的情况下也可以访问共享资源,那么即使其它的线程在使用共享资源前都获取了锁,也还是会出现数据不一致的问题。
  • 互斥变量用 pthread_mutex_t 数据类型表示。在使用互斥变量前必须对它进行初始化,可以把它置为常量 PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用 pthread_mutex_init 函数进行初始化。如果动态地分配互斥量(例如通过调用 malloc 函数),那么在释放内存前需要调用 pthread_mutex_destroy。
  1. 创建及销毁互斥锁
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
// 返回:若成功返回0,否则返回错误编号
  • 要用默认的属性初始化互斥量,只需把 attr 设置为NULL。
  1. 加锁及解锁
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t mutex);//加锁
int pthread_mutex_trylock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);//解锁
// 返回:若成功返回0,否则返回错误编号
  • 如果线程不希望被阻塞,它可以使用 pthread_mutex_trylock 尝试对互斥量进行加锁。如果调用 pthread_mutex_trylock 时互斥量处于未锁住状态,那么 pthread_mutex_trylock 将锁住互斥量,不会出现阻塞并返回 0,否则 pthread_mutex_trylock 就会失败,不能锁住互斥量,而返回 EBUSY。
  • THREAD/demo5.c(这里的互斥锁作用:除 main 线程会穿插,其他线程不会穿插;main、t1、t2、t3 的顺序也不一定)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
/*int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);
int pthread_mutex_destroy(pthread_mutex_t mutex);*/
int g_data = 0;
pthread_mutex_t mutex;//创建一把互斥锁mutex

void *func1(void *arg)
{
	int i;
	pthread_mutex_lock(&mutex);//加锁
	for(i=0;i<5;i++){
		printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
		printf("t1:param is %d\n",*((int *)arg));
		sleep(1);
	}
	pthread_mutex_unlock(&mutex);//解锁
}
void *func2(void *arg)
{
	pthread_mutex_lock(&mutex);

	printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*((int *)arg));

	pthread_mutex_unlock(&mutex);
}
void *func3(void *arg)
{
	pthread_mutex_lock(&mutex);

	printf("t3:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t3:param is %d\n",*((int *)arg));

	pthread_mutex_unlock(&mutex);
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;
	pthread_t t3;//子线程123

	pthread_mutex_init(&mutex, NULL);//初始化互斥锁,属性NULL
	
	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");
	}
	ret = pthread_create(&t2, NULL, func2,(void *)&param);
	if(ret == 0){
		printf("main:create t2 success\n");
	}
	ret = pthread_create(&t3, NULL, func3,(void *)&param);//创建子线程123
	
	printf("main:%ld\n",(unsigned long)pthread_self());//打印主线程id

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);
	pthread_join(t3,NULL);//子线程的等待

	pthread_mutex_destroy(&mutex);//销毁互斥锁

	return 0;
}

5. 互斥锁限制共享资源的访问(441.5)

  • 写一个 test.sh shell 脚本,自动的接续运行./a.out三次

vi test.sh

./a.out
./a.out
./a.out

chmod +x test.sh
./test.sh

  • 写 c 语言程序的方式,自动接续运行./a.out一百次
#include <stdlib.h>
int main(){
	int i = 0;
	for(i=0;i<100;i++){
		system("./thread");
	}
}
  • THREAD/demo6.c(互斥锁:保证 t1 可以运行到 g_data == 3)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>//sleep
#include <stdlib.h>//exit
       
int g_data = 0;
pthread_mutex_t mutex;

void *func1(void *arg)
{
	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));
	
	pthread_mutex_lock(&mutex);
	while(1){
		printf("t1: %d\n",g_data++);	
		sleep(1);
		if(g_data == 3){
			pthread_mutex_unlock(&mutex);
			printf("t1 quit================================\n");
			//pthread_exit(NULL);
			exit(0);
		}
	}
}
void *func2(void *arg)
{
	printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*((int *)arg));
	
	while(1){
		printf("t2: %d\n",g_data);
		pthread_mutex_lock(&mutex);
		g_data++;
		pthread_mutex_unlock(&mutex);	
		sleep(1);
	}
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;

	pthread_mutex_init(&mutex,NULL);

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");
	}
	ret = pthread_create(&t2, NULL, func2,(void *)&param);
	if(ret == 0){
		printf("main:create t2 success\n");
	}

	printf("main:%ld\n",(unsigned long)pthread_self());
	while(1){
		printf("main: %d\n",g_data);	
		sleep(1);
	}

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);
	pthread_mutex_destroy(&mutex);

	return 0;
}

6. 什么情况造成死锁(442.6)(*面试会问)

  • 前提条件:两把锁,当线程 A 获得一把锁后,想获得另外一把锁,而线程 B 手里握着线程 A 想要获得的那把锁,同时也想要拿线程 A 的一把锁,导致线程 A 和线程 B 都想要拿到对方手里的那把锁,都不肯往下去解锁,导致线程AB的死锁
  • THREAD/demo7.c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>//sleep

int g_data = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;

void *func1(void *arg)
{
	int i;

	pthread_mutex_lock(&mutex);
	sleep(1);
	pthread_mutex_lock(&mutex2);
	
	for(i=0;i<5;i++){
		printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
		printf("t1:param is %d\n",*((int *)arg));
		sleep(1);
	}
	pthread_mutex_unlock(&mutex);
}
void *func2(void *arg)
{	
	pthread_mutex_lock(&mutex2);
	sleep(1);
	pthread_mutex_lock(&mutex);

	printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*((int *)arg));

	pthread_mutex_unlock(&mutex);
}
void *func3(void *arg)
{
	pthread_mutex_lock(&mutex);

	printf("t3:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t3:param is %d\n",*((int *)arg));

	pthread_mutex_unlock(&mutex);
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;
	pthread_t t3;

	pthread_mutex_init(&mutex, NULL);
	pthread_mutex_init(&mutex2, NULL);
	
	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
		printf("main:create t1 success\n");
	}
	ret = pthread_create(&t2, NULL, func2,(void *)&param);
	if(ret == 0){
		printf("main:create t2 success\n");
	}
	ret = pthread_create(&t3, NULL, func3,(void *)&param);
	printf("main:%ld\n",(unsigned long)pthread_self());

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);

	pthread_mutex_destroy(&mutex);
	pthread_mutex_destroy(&mutex2);

	return 0;
}

7. 线程条件控制实现线程的同步(443.7)

与条件变量相关API

  • 条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
  • 条件本身是由互斥量保护的。线程在改变条件状态前必须首先锁住互斥量,其他线程在获得互斥量之前不会察觉到这种改变,因为必须锁定互斥量以后才能计算条件。
  • 条件变量使用之前必须首先初始化,pthread_cond_t 数据类型代表的条件变量可以用两种方式进行初始化,可以把常量 PTHREAD_COND_INITIALIZER 赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用 pthread_cond_destroy 函数对条件变量进行去除初始化(deinitialize)。
  1. 创建及销毁条件变量
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号
  • 除非需要创建一个非默认属性的条件变量,否则 pthread_cont_init 函数的attr参数可以设置为NULL。
  1. 等待
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, cond struct timespec *restrict timeout);
// 返回:若成功返回0,否则返回错误编号
  • pthread_cond_wait 等待条件变为真。如果在给定的时间内条件不能满足,那么会生成一个代表一个出错码的返回变量。传递给 pthread_cond_wait 的互斥量对条件进行保护,调用者把锁住的互斥量传给函数。函数把调用线程放到等待条件的线程列表上,然后对互斥量解锁,这两个操作都是原子操作。这样就关闭了条件检查和线程进入休眠状态等待条件改变这两个操作之间的时间通道,这样线程就不会错过条件的任何变化。pthread_cond_wait 返回时,互斥量再次被锁住。
  • pthread_cond_timedwait 函数的工作方式与 pthread_cond_wait 函数类似,只是多了一个 timeout。timeout 指定了等待的时间,它是通过timespec结构指定。
  1. 触发
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t *cond);//接受者有一条
int pthread_cond_broadcast(pthread_cond_t *cond);//接受者有多条
// 返回:若成功返回0,否则返回错误编号
  • 这两个函数可以用于通知线程条件已经满足。pthread_cond_signal 函数将唤醒等待该条件的某个线程,而 pthread_cond_broadcast 函数将唤醒等待该条件的所有进程。
  • 注意一定要在改变条件状态以后再给线程发信号。

课外自学(用来做数据缓冲区)

代码

  • THREAD/demo8.c(动态初始化,t2 加到 3 运行 t1 cond 后的)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>//sleep
#include <stdlib.h>//exit

int g_data = 0;
pthread_mutex_t mutex;//创建一把互斥锁mutex
pthread_cond_t cond;//创建一个条件变量cond

void *func1(void *arg)
{
	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));
	static int cnt = 1;
	
	while(1){
		pthread_cond_wait(&cond,&mutex);//等待(发生在锁之上的)条件的发话
		printf("t1 run================================\n");
		printf("t1: %d\n",g_data);	
		g_data = 0;
		sleep(1);
		if(cnt++ == 10){//子线程运行10次退出
			exit(1);
		}
	}
}
void *func2(void *arg)
{
	printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*((int *)arg));
	
	while(1){
		printf("t2: %d\n",g_data);
		pthread_mutex_lock(&mutex);
		g_data++;
		if(g_data == 3){
			pthread_cond_signal(&cond);//到3时运行cond后面的
		}
		pthread_mutex_unlock(&mutex);	
		sleep(1);
	}
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;

	pthread_mutex_init(&mutex,NULL);//动态初始化(互斥锁),属性NULL
	pthread_cond_init(&cond,NULL);//动态初始化(条件变量),属性NULL

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
//		printf("main:create t1 success\n");
	}
	ret = pthread_create(&t2, NULL, func2,(void *)&param);
	if(ret == 0){
//		printf("main:create t2 success\n");
	}
//	printf("main:%ld\n",(unsigned long)pthread_self());

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);//子线程的等待

	pthread_mutex_destroy(&mutex);//销毁互斥锁
	pthread_cond_destroy(&cond);//销毁条件变量
	return 0;
}
  • THREAD/demo9.c(宏的方式,静态初始化,t2 加到 3 运行 t1 cond 后的)
  • Linux线程之一次性初始化
    • https://blog.csdn.net/lixiaogang_theanswer/article/details/82557235
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>//sleep
#include <stdlib.h>//exit

int g_data = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//静态初始化

void *func1(void *arg)
{
	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int *)arg));
	static int cnt = 0;
	
	while(1){
		
		pthread_cond_wait(&cond,&mutex);
		printf("t1 run================================\n");

		printf("t1: %d\n",g_data);	
		g_data = 0;
		sleep(1);
		if(cnt++ == 10){
			exit(1);
		}
	}
}
void *func2(void *arg)
{
	printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*((int *)arg));
	
	while(1){
		printf("t2: %d\n",g_data);
		pthread_mutex_lock(&mutex);
		g_data++;
		if(g_data == 3){
			pthread_cond_signal(&cond);
		}
		pthread_mutex_unlock(&mutex);	
		sleep(1);
	}
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;

//	pthread_mutex_init(&mutex,NULL);
//	pthread_cond_init(&cond,NULL);

	ret = pthread_create(&t1, NULL, func1,(void *)&param);
	if(ret == 0){
//		printf("main:create t1 success\n");
	}
	ret = pthread_create(&t2, NULL, func2,(void *)&param);
	if(ret == 0){
//		printf("main:create t2 success\n");
	}
//	printf("main:%ld\n",(unsigned long)pthread_self());

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值