多线程同步

</pre><p>一、互斥锁</p><p><pre name="code" class="cpp">#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

int globle_i = 50;
pthread_mutex_t globle_mutex;
void* thread_func(){
  // pthread_mutex_lock(&globle_mutex);  //如果不加锁,仍然可以改变globel_i,所以需要自己控制好锁
   while(globle_i != 0)
    {
        if( globle_i != 0)  
        {
            globle_i  = globle_i  -1; 
        }
        printf("in new thread globle_i = %d\n", globle_i);
        usleep(1);
    }
   //pthread_mutex_unlock(&globle_mutex);
    return NULL;
}
int main(){
   pthread_t thread;
   int res = -1;
   res = pthread_mutex_init(&globle_mutex, NULL);
   if(res != 0){
        perror("ptherad_mutex_init failed!\n"); 
        exit(EXIT_FAILURE);
   }
    
   res = pthread_create(&thread, NULL, thread_func, NULL);
   if(res != 0)
   {
        perror("ptherad_mutex_init failed!\n"); 
        exit(EXIT_FAILURE);
   }

   pthread_mutex_lock(&globle_mutex);
   while(globle_i != 0)
    {
        if( globle_i != 0)  
        {
            globle_i  = globle_i  -1; 
        }
        else{
            printf("no more\n"); 
        }
        printf("in the main thread globle_i=%d\n", globle_i);
        usleep(1);
    }
   pthread_mutex_unlock(&globle_mutex);

   res = pthread_join(thread, NULL);
   if(res != 0)
   {
       perror("pthread_join failed\n");
        exit(EXIT_FAILURE);
   }

   printf("thread joined\n");

   pthread_mutex_destroy(&globle_mutex);
    return 0;
}

二、条件变量


三、信号量


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Rust是一种现代的系统级编程语言,它提供了内存安全、并发性和高性能的特性。在Rust中,多线程同步是通过标准库中的原子类型和同步原语来实现的。 Rust的原子类型(Atomic Types)是一种特殊的数据类型,可以在多个线程之间进行原子操作,保证操作的原子性。常见的原子类型包括AtomicBool、AtomicIsize、AtomicUsize等。通过原子类型,可以实现多线程之间的共享数据的安全访问。 除了原子类型,Rust还提供了一些同步原语,用于实现多线程之间的同步和互斥。其中最常用的是Mutex和RwLock。Mutex提供了互斥锁机制,确保在同一时间只有一个线程可以访问被锁定的数据。RwLock则提供了读写锁机制,允许多个线程同时读取数据,但只允许一个线程进行写操作。 使用Rust进行多线程同步的一般步骤如下: 1. 导入所需的库:在Rust中,需要使用std::sync模块中的相关类型和函数来实现多线程同步。 2. 创建共享数据:定义需要在多个线程之间共享的数据结构。 3. 使用原子类型:对需要在多个线程之间进行原子操作的数据使用原子类型进行封装。 4. 使用同步原语:使用Mutex或RwLock对需要进行互斥访问的数据进行封装。 5. 创建线程:使用std::thread模块创建多个线程,并传递共享数据的引用给每个线程。 6. 进行同步操作:在每个线程中,使用Mutex的lock方法获取锁,并对共享数据进行操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值