What is multi-thread security?

Source: Internet
Author: User
For multi-threaded programming, many people are not clear about the concept. When writing code, they either lock everywhere and affect performance. It is also easy to get down to inexplicable deadlocks. Others are far away from multithreading.

So the most important thing to learn multi-threaded programming is not to learn API, but to understand what is multi-threaded secure code.

Starting from the example

# Include <windows. h>
# Include <process. h>

Long global1 = 0;
Volatile long global2 = 0;

Class myclass
{
Public:
Myclass (): m (0)
{
++ M;
}

Int fun (int v)
{
Return m + V; // ----------- 9
}

Void set (int v)
{
M = V; // ------------- 10
}
Int m;
};

Myclass global_object; // ------------- 8

Unsigned int _ stdcall thread_fun1 (void * PARAM)
{
Static int static2 = 0;
Static myclass static_object; // -------- 6
Int local1 = 0;

+ + Local1; // ------- 1
+ + Static2; // ------- 2
+ + Global1; // ------- 3
+ + Global2; // ------- 4
Interlockedincrement (& global1); // -------- 5

Local1 = global_object.fun (local1); // ---------- 7

Global_object.set (local1); // --------------- 11

Return 0;
}

Unsigned int _ stdcall thread_fun2 (void * PARAM)
{
+ + Global1; // ------- 3
+ + Global2; // ------- 4
Interlockedincrement (& global1); // -------- 5

Global_object.set (1); // ----------- 11
Return 0;
}

Int main ()
{
Handle thread1 = (handle) _ beginthreadex (0, 0, & thread_fun1, 0, 0); // thread 1
Handle thread2 = (handle) _ beginthreadex (0, 0, & thread_fun1, 0, 0); // thread 2
Handle thread3 = (handle) _ beginthreadex (0, 0, & thread_fun2, 0, 0); // thread 3

Waitforsingleobject (thread1, infinite );
Waitforsingleobject (thread2, infinite );
Waitforsingleobject (thread3, infinite );

Return 0;
}

1. Local Use of local variables is safe
Why? Because each thread has its own running stack, and the local variable is stored in the stack, everyone will not interfere.
So code 1
Int local1;
++ Local1;
IS SECURE

2. multi-thread read/write of global native variables is insecure
The global variable is in heap.
Long global1 = 0;
++ Global2;
++ This operation is actually divided into two parts: read and write.
MoV ECx, global
Add ECx, 1
MoV global, ECx
So code 3 is insecure.

3. multi-thread reading and writing of static function variables is also insecure.
Same as 2
Therefore, code 2 is insecure.

4. Can volatile ensure the security of global Integer Variables in multiple threads?
No.
Volatile only warns compiler not to optimize this variable. Each time we take a value from memory, rather than from register.
So code 4 is not secure.

5. interlockedincrement ensures the auto-increment atomicity of Integer Variables
Therefore, Code 5 is safe.

6. Is the initialization of function static object safe with multiple threads?
No.
The famous Meyer Singleton is NOT thread-safe.
Object & getinstance ()
{
Static object O;
Return O;
}
The object may be initialized multiple times.
So Code 6 is insecure.

7. On 32 machines, assign is an atomic four-byte integer.
For example
I = 10; // thread1
I = 4; // thread2
It does not cause the I value to be unknown, either 10 or 4.

Let others know about it.

The magic weapon to write a good multi-thread security program is encapsulation, which ensures that data is securely accessed.
Security:
Local variables> member variables> global variables

Feedback # Re: What is multi-thread security reply more comments

By Nanami about stack and stack issues, not necessarily on the stack is not safe.
Type struct _ ABC
{
Int;
Int B;
Int C;
} ABC, * pabc;

ABC myabc;
Pabc pmyabc = new myabc;

The objects of the two variables myabc and pmyabc are completely different. Using New will be allocated on the stack, and directly declaring the variables will be allocated on the stack. The heap is relatively small, but the stack is large. For some large class objects, the stack is usually allocated, but the stack performance is inferior to the heap performance, small objects such as int are directly generated on the stack. Each thread has its own independent stack and stack. The global variables are generated on the public stack, so they are not secure. The independent heap and stack of threads are thread-safe and irrelevant.

The operation thread tries its best to use entercriticalsection and leavecriticalsection. The performance is better than that of mutex, especially when a large number of locks and locks are obvious.

# To: Nanami replies to more comments

By James clarify the terms
Heap
STACK: Stack

I didn't say heap is not safe.

In fact, whether it is in the stack or heap, it is not a normal memory address, there is no special place, as long as multiple threads do not lock the read and write will cause performance problems.

# Re: What is multi-thread security reply more comments

By vender to Nanami:

Some questions are discussed with you. From the perspective of your speech, you have reversed the heap and stack. You mentioned

"New will be allocated on the stack"
-- To be exact, it is on the heap (of course, the actors who reload new are not necessarily)

"Directly declaring variables will be allocated on the stack"
-- Fully local area (for example, any function or variable defined outside the class) and static variables (for example, with a static indicator) are allocated (specifically ing) in the static storage area (which can be considered to be the same as the memory area when the executable code is running), Dynamic Allocation occurs on the heap (provided that no allocation operators such as new are reloaded ), allocate local variables on the stack

"The stack is relatively small, but the stack is large"
-- In this case, the stack size is not the difference between the stack size and stack size. Generally, the stack size is determined. Once the stack is set up, the stack size will be fixed and overflow will occur, heap can apply for more information from the operating system at any time,

"For some large class objects, they are generally allocated on the stack"
-- As we can see from the previous point, it should be "for some large class objects, usually allocated on the heap rather than on the stack"

"The stack performance is inferior to the heap performance. Small objects such as int are directly generated on the stack"
-- In essence, there is no performance difference. At most, because the memory on the heap can only be accessed through pointers and references, more memory addressing is required.

"Each thread has its own independent heap and stack. The global variables are generated on the public stack, so they are not secure. The independent heap and stack of threads are thread-safe and irrelevant ."
-- Security and anxiety: Check whether the object is a "critical resource" (see the operating system book). No matter where the object is allocated, it is best for Mr. James to make a sentence: "In fact, no matter whether it is in the stack or heap, it is not a normal memory address, there is no special place, as long as multiple threads do not lock the read/write will cause performance problems. ", Of course, the "performance problem" mentioned by Tom must be a written mistake. I think he refers to the "security problem" # Re: What is multi-thread security? reply to more comments

By Tony agreed to go upstairs! # Re: What is multi-thread security reply more comments

By Lianhua butterfly Nanami

I am sweating your foundation .....

# Re: What is multi-thread security reply more comments

By passer-by B by Vender
The statement is basically correct (the meaning of this sentence is incorrect ~) # Re: What is multi-thread security reply more comments

By hsen 2. Global native variable multi-thread read/write is not necessarily insecure, as long as the code is changed to this way it is safe
Assume struct t
T * global_t;

Thread code
T * Nt = new T;
T * temp = & global_t;
Do {
Memcpy (NT, global_t, sizeof (t ));
// Modify
} While (! CAS (& global_t, temp, NT ));

CAs can be implemented using xchgcmp commands # Re: What is multi-thread security reply more comments

By noflybird it is inevitable to use multi-threaded locks.
Locks are used to share data. It is easy to read and write.
As for the basis of your discussion .. I will not make any comments. # Re: What is multi-thread security reply more comments

Don't say anything you don't know about anonymous, don't say something you're not sure about, or mislead others. # Re: What is multi-thread security reply more comments

By Lu renjia multi-thread lock read/write ....

What if it's just reading? For example, if the Global Object List is used to read list. Count, is it safe if no lock is applied?

# Re: What is multi-thread security reply more comments

By Wu reading will not be unsafe, but will read outdated things. # Re: What is multi-thread security reply more comments

By the basic concept of the new master, really a "sweat" word.

Upstairs, you said, "reading is not unsafe, but reading outdated things." This is a pseudo proposition! When will it be out of date? No answer. # Re: What is multi-thread security reply more comments

From, passers-by B should clarify the concept first and then explain it again. This article is still removed. As someone mentioned above, "Everything is reversed." Although it is a bit exaggerated, but at least the two basic concepts of heap and stack are indeed reversed ...... Earth is too dangerous. Let me go back to Mars # Re: What is multi-thread security reply more comments

By James some of the concepts I mentioned in this article, I think they are correct, although it is a bit messy.
If you have any objection, You can reference and point out the error. # Re: What is multi-thread security reply more comments

2006-11-28 by s778025 profound understanding of the problem...
Dare you say...
More... # Re: What is multi-thread security reply more comments

By bryanj I think it is very good for beginners. There are no errors. # Re: What is multi-thread security reply more comments

By yoyolion I did not find any problems with the foundation of the landlord. Ask passers-by B for a lecture.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.