117.info
人生若只如初见

c语言两个线程之间怎么通信

在C语言中,可以使用以下方法实现两个线程之间的通信:

  1. 全局变量:两个线程可以共享一个全局变量,并通过对该变量的读写来进行通信。需要注意的是,对全局变量的读写需要加锁以避免竞争条件。

示例代码:

#include 
#include 
int shared_variable = 0;
pthread_mutex_t mutex;
void* thread1(void* arg) {
pthread_mutex_lock(&mutex);
shared_variable = 1;  // 修改共享变量
pthread_mutex_unlock(&mutex);
return NULL;
}
void* thread2(void* arg) {
pthread_mutex_lock(&mutex);
printf("Shared variable: %d\n", shared_variable);  // 读取共享变量
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
  1. 条件变量:一个线程等待另一个线程发出特定信号后才继续执行。其中,等待线程使用pthread_cond_wait()阻塞自己,发送信号的线程使用pthread_cond_signal()pthread_cond_broadcast()发送信号。

示例代码:

#include 
#include 
int shared_variable = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread1(void* arg) {
pthread_mutex_lock(&mutex);
shared_variable = 1;  // 修改共享变量
pthread_cond_signal(&cond);  // 发送信号给等待的线程
pthread_mutex_unlock(&mutex);
return NULL;
}
void* thread2(void* arg) {
pthread_mutex_lock(&mutex);
while (shared_variable == 0) {
pthread_cond_wait(&cond, &mutex);  // 等待信号
}
printf("Shared variable: %d\n", shared_variable);  // 读取共享变量
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}

以上是两种常见的线程之间通信的方式,具体使用哪种方式取决于具体的需求和场景。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fec48AzsLBAZfB1A.html

推荐文章

  • c语言socket函数有哪些参数

    C语言的socket函数有五个参数: domain:表示通信的域,常用的值有AF_INET(IPv4协议)和AF_INET6(IPv6协议)。 type:表示通信的类型,常用的值有SOCK_STREAM(...

  • c语言怎么输出100以内素数

    以下是一个用C语言编写的输出100以内素数的程序:
    #include int main() {
    int i, j, is_prime;
    printf("Prime numbers between 1 and 100:\n");<...

  • c语言怎么实现随机数生成1到100

    在C语言中,可以使用rand()函数生成随机数。该函数返回一个0到RAND_MAX(通常是32767)之间的整数。可以使用取余运算符将生成的随机数缩放到1到100之间。
    下...

  • c语言数组初始化的方法是什么

    C语言中数组的初始化方法有多种,具体方法取决于数组的类型和使用场景。以下是常见的数组初始化方法: 逐个赋值初始化:逐个为数组的每个元素赋值。 int arr[5];...

  • python气象数据处理的方法是什么

    在Python中,可以使用一些常用的库和方法来处理气象数据,其中包括: NumPy:用于处理数值计算和数组操作,可以用来处理气象数据的数值计算和数组操作。 Pandas:...

  • JavaScript Array constructor属性有什么用

    JavaScript的Array构造函数属性是用于返回创建Array对象时使用的构造函数的引用。
    它有以下用途: 获取数组对象的构造函数:可以通过Array构造函数属性来获...

  • JavaScript数组Const怎么使用

    在JavaScript中,const关键字用于声明一个常量,它可以用于声明数组。声明一个用const关键字声明的数组后,数组的引用不能被修改,但是数组的内容可以被修改。以...

  • ASP.NET DayHeaderStyle属性怎么用

    ASP.NET DayHeaderStyle属性用于设置日历控件中每个日期标题的样式。
    例如,要设置日历控件的日期标题为红色并设置字体大小为12px,可以通过以下方式设置Da...