条件变量的使用注意

linux下多线程编程时,随着主线程的结束,在整个 进程结束时,仍然有正在运行的子线程,那么这些子线程也会一并结束(注意,主线程的结束并不会影响子线程的结束),但是当子线程中有条件变量正在wait时,会出现~condition_variable_any():Assertion '!pthread_mutex_destroy(&internal_mutex)' failed.的错误,大概意思是说互斥变量在销毁时出现了异常。一个解决的办法是在 进程结束前 手动对这个条件变量所等待的信号进行notify唤醒操作,直到可以确定在 进程结束前该条件变量所在的线程已经从等待状态转入了运行状态,那么相关变量就能正常析构销毁了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用多线程编程时,条件变量(Condition Variable)是一种重要的同步机制,用于线程之间的通信和协调。下面是一个使用条件变量的简单示例: ```c #include <stdio.h> #include <pthread.h> // 全局变量和条件变量 int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 生产者线程函数 void* producer(void* arg) { for (int i = 0; i < 5; ++i) { pthread_mutex_lock(&mutex); // 加锁 // 如果 count 不为 0,等待消费者消费 while (count != 0) { pthread_cond_wait(&cond, &mutex); } // 生产物品 count++; printf("Producer produced an item. Total items: %d\n", count); pthread_mutex_unlock(&mutex); // 解锁 pthread_cond_signal(&cond); // 通知消费者可以消费 } pthread_exit(NULL); } // 消费者线程函数 void* consumer(void* arg) { for (int i = 0; i < 5; ++i) { pthread_mutex_lock(&mutex); // 加锁 // 如果 count 为 0,等待生产者生产 while (count == 0) { pthread_cond_wait(&cond, &mutex); } // 消费物品 count--; printf("Consumer consumed an item. Total items: %d\n", count); pthread_mutex_unlock(&mutex); // 解锁 pthread_cond_signal(&cond); // 通知生产者可以生产 } pthread_exit(NULL); } int main() { pthread_t producerThread, consumerThread; // 创建生产者和消费者线程 pthread_create(&producerThread, NULL, producer, NULL); pthread_create(&consumerThread, NULL, consumer, NULL); // 等待线程结束 pthread_join(producerThread, NULL); pthread_join(consumerThread, NULL); // 销毁条件变量和互斥锁 pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); return 0; } ``` 在上面的示例中,我们使用了一个全局变量 `count` 来表示生产者生产或消费者消费的物品数量。在保证线程安全的前提下,生产者通过条件变量判断是否可以继续生产,消费者通过条件变量判断是否可以继续消费。 注意,在使用条件变量时,需要先加锁(`pthread_mutex_lock`),然后使用`pthread_cond_wait`等待条件满足,直到其他线程通过`pthread_cond_signal`或者`pthread_cond_broadcast`通知当前线程可以继续执行。在满足某个条件后,需要解锁(`pthread_mutex_unlock`)以允许其他线程进入临界区。 以上是条件变量的一个简单使用例子,希望能帮助你理解条件变量的基本用法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值