一个段实现多线程互斥的代码

             try
                {
                   //try enter Obj within timespan senconds.
                    if (System.Threading.Monitor.TryEnter(Obj, TimeSpan.FromSeconds(timespan)))
                    {
                              //do something with Obj

                    }
                }
                catch (Exception e)
                {
                    this.dispInfo(e.Message);
                    return;
                }
                finally
                {
                    Monitor.Exit(Obj);  //不管是正常还是发生错误,都得释放对象

                } 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多线程编程中,为了防止多个线程同时修改同一个变量,需要使用互斥锁来保证线程的安全性。下面是使用消息机制实现多个线程互斥修改同一个变量的示例代码: ```python import threading import queue # 定义一个共享变量 count = 0 # 定义一个消息队列 msg_queue = queue.Queue() # 定义一个互斥锁 mutex = threading.Lock() # 定义一个线程类 class MyThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): global count while True: # 从消息队列中获取消息 msg = msg_queue.get() if msg == "quit": break # 加锁 mutex.acquire() # 修改共享变量 count += 1 print(self.name, "count:", count) # 解锁 mutex.release() # 创建多个线程 thread1 = MyThread("Thread1") thread2 = MyThread("Thread2") thread3 = MyThread("Thread3") # 启动线程 thread1.start() thread2.start() thread3.start() # 往消息队列中添加消息 for i in range(10): msg_queue.put("msg") # 等待所有线程执行完毕 thread1.join() thread2.join() thread3.join() # 往消息队列中添加退出消息 msg_queue.put("quit") msg_queue.put("quit") msg_queue.put("quit") ``` 在上面的代码中,我们定义了一个共享变量 `count`,多个线程互斥地修改这个变量。为了保证线程的安全性,我们使用了互斥锁 `mutex` 来保证同一时间只有一个线程能够修改 `count` 变量。 在线程的 `run` 方法中,我们使用了一个无限循环来不断从消息队列中获取消息,并根据消息来修改共享变量。在修改共享变量之前,我们需要先加锁 `mutex.acquire()`,在修改完毕后,需要解锁 `mutex.release()`。 在主线程中,我们往消息队列中添加了多个消息,等待所有线程执行完毕后,再往消息队列中添加退出消息,让所有线程退出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值