linux线程同步

本文通过一个C语言程序实例介绍了如何使用pthread库实现多线程间的同步操作及条件变量的应用。程序中创建了两个线程,一个用于写入数据到共享字符串并通知读取线程,另一个用于等待数据可用后读取并输出该字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人测试:

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

char str[100];
pthread_mutex_t mutex_read,mutex_write;
pthread_cond_t cond_read,cond_write;
void* p1_func(void* arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex_read);
    pthread_cond_wait(&cond_read,&mutex_read);
    printf("\nstr=%s\n",str);
    pthread_cond_signal(&cond_write);
    pthread_mutex_unlock(&mutex_read);
  }
}
void* p2_func(void* arg)
{
  int i = 0;
  printf("\np2_func\n");
  while(1)
  {
     i++;
     if(i%10==0)
     {
//       printf("\n%d 10\n",i);
       pthread_mutex_lock(&mutex_write);
       sprintf(str,"lock %d",i);
       pthread_cond_signal(&cond_read);
       pthread_cond_wait(&cond_write,&mutex_write);
       pthread_mutex_unlock(&mutex_write);
     }
     sleep(1);
     printf("\n%d\n",i);
  }
}
int main()
{
  pthread_t p1;
  pthread_t p2;
  pthread_mutex_init(&mutex_read,NULL);
  pthread_cond_init(&cond_read,NULL);
  pthread_mutex_init(&mutex_write,NULL);
  pthread_cond_init(&cond_write,NULL);
  pthread_create(&p1,NULL,p1_func,NULL);
  pthread_create(&p2,NULL,p2_func,NULL); 
  pthread_join(p1,NULL);
  pthread_join(p2,NULL);
  pthread_mutex_destroy(&mutex_read);
  pthread_cond_destroy(&cond_read);
  pthread_mutex_destroy(&mutex_write);
  pthread_cond_destroy(&cond_write);
  return 0;
}


### Linux环境下的多线程同步方法 #### 互斥锁实现线程安全 在Linux环境中,互斥锁是一种常用的同步机制,用于保护临界区内的代码免受多个线程并发访问的影响。同一时刻只有一个线程可以持有某个互斥锁并对其进行操作;当一个线程试图锁定已被占用的互斥锁时,该线程会被阻塞直至当前持有的线程解锁[^2]。 ```c #include <pthread.h> // 定义互斥锁 pthread_mutex_t mutex; void init_mutex() { pthread_mutex_init(&mutex, NULL); } void lock_resource() { pthread_mutex_lock(&mutex); // 尝试获取锁,如果失败则会阻塞在此处 } void unlock_resource() { pthread_mutex_unlock(&mutex); // 解锁以便其他等待中的线程可以获得此锁 } ``` #### 使用条件变量进行线程间的协作 除了互斥锁外,在某些场景下还需要更复杂的逻辑来控制不同线程之间的交互过程,这时就可以引入条件变量作为辅助工具。通过与互斥锁配合使用,可以让某一线程基于特定条件的发生与否决定是否继续运行还是进入休眠状态,从而达到更加精细粒度上的调度效果[^3]。 ```c #include <pthread.h> #include <stdio.h> #include <unistd.h> pthread_cond_t cond; pthread_mutex_t mutex; int ready = 0; // 假设这是一个共享资源的状态标志位 void* waiting_thread(void *arg){ while(1){ pthread_mutex_lock(&mutex); if(!ready){ printf("Waiting thread is going to wait.\n"); pthread_cond_wait(&cond,&mutex); // 等待直到被通知 } printf("Condition met! Ready value:%d\n",ready); pthread_mutex_unlock(&mutex); sleep(1); // 模拟处理时间 } return NULL; } void* signaling_thread(void *arg){ sleep(5); // 让另一个线程先启动并开始等待 pthread_mutex_lock(&mutex); ready=1; // 改变条件 printf("Signaling thread changes condition and signals others.\n"); pthread_cond_signal(&cond); // 发送信号给正在等待的线程 pthread_mutex_unlock(&mutex); return NULL; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值