Write MultithreadingProgramIs a variable locked?
Do deadlocks occur when the lock order of several locks is different?
Here is a small tool that can test whether your logic is correct.
This is a C ++ command line program with over 500 lines. Of course, it does not understand C/C ++.CodeAnd cannot simulate program running. Therefore, you need to rewrite the logic to be tested into a syntax format that can recognize it.
(Currently, only lock/unlock operations are allowed to process lock types)
For example, the following program test1.txt:
VaR list;
VaR lock1: lock;
Thread 1:
Read list;
Thread 2:
Write list;
After the tool is executed, it displays:
> Threadchk.exe test1.txt
Line: 11 unsafe-Access of variable 'LIST'
Thread: 1 at line: 6
* Thread: 2 at line: 11
Done
That is to say, when thread 1 is executed to 6th rows and thread 2 is executed to 11th rows, it will have insecure references to the list variable.
Program Rewriting and lock:
VaR list;
VaR lock1: lock;
Thread 1:
Lock lock1;
Read list;
Unlock lock1;
Thread 2:
Lock lock1;
Write list;
Unlock lock1;
Execute the tool again:
> Threadchk.exe test1.txt
Done
As shown in, there is no problem.
For example, we all know that two locks cause deadlocks:
VaR list;
VaR lock1: lock;
VaR lock2: lock;
Thread 1:
Lock lock1;
Lock lock2;
Read list;
Unlock lock1;
Unlock lock2;
Thread 2:
Lock lock2;
Lock lock1;
Write list;
Unlock lock1;
Unlock lock2;
The running result is as follows:
> Threadchk.exe test1.txt
Error: deadlock of lock lock1 Detected
Thread: 1 at line: 8
* Thread: 2 at line: 16
Done
Adjust the lock sequence and change thread 2:
Lock lock1;
Lock lock2;
Write list;
Unlock lock2;
Unlock lock1;
If you try again, there will be no problem.
In this example, there are few threads and variables, and the actual situation is much more complicated. For example, the triplicate lock cross-reference is not described here. If you encounter multiple threads, use this tool to verify your ideas.
Deadlock and Security TestingAlgorithmThey are all good examples. Tools and source code are listed in:
Http://download.csdn.net/source/3057588