Thread and shared lock

1.主线程执行,开启5个子线程,进行计数,没有使用mutex锁住,由于没有lock住,每个线程对全局变量的操作错乱,结果如下:

 1 """
 2 synchronize access to stdout: because it is shared global
 3 thread outputs may be intermixed if not syschronized
 4 """
 5 import thread,time
 6 global num                                  #global var to be used by many threads
 7 num=0
 8
 9 def cnt(id,count):                          # function run in threads
10     for i in range(count):
11         global num
12         #mutex.acquire()                     # lock the share var before execute
13         num +=1
14         time.sleep(0.5)                     # simulate read work
15         print(‘[%s] num= %s\n‘ %(id,num))   #print isn‘t interrupted now
16         #mutex.release()                     #release the lock for the other thread
17
18 if __name__ =="__main__":
19     #mutex=thread.allocate_lock()            #make a global mutex for lock
20     for i in range(5):                      #spawm 5 threads
21         thread.start_new_thread(cnt,(i,3))  #start threads
22     time.sleep(8)                          # wait for spawn thread work done,don‘t exit too early
23
24     print(‘main thread exitting‘)

2.把mutex 注释打开,有了mutex变量,每一个线程进入都会独占num变量,结果如下:

 1 """
 2 synchronize access to stdout: because it is shared global
 3 thread outputs may be intermixed if not syschronized
 4 """
 5 import thread,time
 6 global num                                  #global var to be used by many threads
 7 num=0
 8
 9 def cnt(id,count):                          # function run in threads
10     for i in range(count):
11         global num
12         mutex.acquire()                     # lock the share var before execute
13         num +=1
14         time.sleep(0.5)                     # simulate read work
15         print(‘[%s] num= %s\n‘ %(id,num))   #print isn‘t interrupted now
16         mutex.release()                     #release the lock for the other thread
17
18 if __name__ =="__main__":
19     mutex=thread.allocate_lock()            #make a global mutex for lock
20     for i in range(5):                      #spawm 5 threads
21         thread.start_new_thread(cnt,(i,3))  #start threads
22     time.sleep(8)                          # wait for spawn thread work done,don‘t exit too early
23
24     print(‘main thread exitting‘)

3.如果把time.sleep(6)注释掉或者子线程没有执行完毕,而主线程sleep的时间一到,主线程直接退出而不等待子线程执行完毕,结果如下:

a.主线程不等待,则直接退出

b.主线程只等待3s,而5个子线程需要7.5s,所以num只计数5.

4.设定有效等待时间和锁之后,主线程等待所有子线程执行结束才退出,结果如下:

时间: 2024-12-26 21:04:54

Thread and shared lock的相关文章

C++ 11 thread 基础用法 lock unlock join mutex joinable lock_guard unique_lock condition_variable wait notify_one notify_all asnyc future packaged_task promise

#include "pch.h"#include<iostream> #include<string> #include<vector> #include<list> // 线程相关头文件#include<thread>#include<mutex> #include<future>using namespace std; static int res = 0; //共享变量 演示使用互斥量读写. mu

43_2013年11月22日 线程池 Socket(Thread Lock Process 摇奖 线程池ThreadPool)

1>模拟线程池,生产者消费者问题 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Product { class Program { static void Main(string[] args) { //创建一个池子 MyConncetion[]

Thread in Java

References: [1]. http://www.javaworld.com/article/2074481/java-concurrency/java-101--understanding-java-threads--part-4---thread-groups--volatility--and-threa.html?page=2 1. Volatility Volatility, that is, changeability, describes the situation where

Java Concurrency In Practice -Chapter 2 Thread Safety

Writing thread-safe code is managing access to state and in particular to shared, mutable state. Object's state is its data, stored in state variables such as instance or static fields. Whether an object needs to be thread-safe depends on whether it

Do waiting or suspended tasks tie up a worker thread?

https://blogs.msdn.microsoft.com/askjay/2012/07/29/do-waiting-or-suspended-tasks-tie-up-a-worker-thread/ jamesaskJuly 29, 20120 I had a discussion the other day with someone about worker threads and their relation to tasks.  I thought a quick demo mi

How to Analyze Java Thread Dumps--reference

原文地址:http://architects.dzone.com/articles/how-analyze-java-thread-dumps The Performance Zone is presented by AppDynamics. AppDynamics is a leaders in the APM space with massive cost reductions for users. The content of this article was originally wri

How to Analyze Java Thread Dumps

When there is an obstacle, or when a Java based Web application is running much slower than expected, we need to use thread dumps. If thread dumps feel like very complicated to you, this article may help you very much. Here I will explain what thread

Java并发(2):Lock

在上一篇文章中我们讲到了如何使用关键字synchronized来实现同步访问.本文我们继续来探讨这个问题,从Java 5之后,在java.util.concurrent.locks包下提供了另外一种方式来实现同步访问,那就是Lock. 也许有朋友会问,既然都可以通过synchronized来实现同步访问了,那么为什么还需要提供Lock?这个问题将在下面进行阐述.本文先从synchronized的缺陷讲起,然后再讲述java.util.concurrent.locks包下常用的有哪些类和接口,最后

Lock使用实例

using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LockUse { //使用Lock(this)的类 class MyClass {         //声明一个bool变量,用于判断是否上