当前位置:网站首页>C multithreading learning note 2
C multithreading learning note 2
2022-06-10 13:58:00 【HollowKnightZ】
Use Thread Some do's and don 'ts
Thread visible
AllocateDataSlot、SetData、 GetData
variable var => thread t1,t2
(1) t1,t2 share var => public Yes “ lock ” The problem of
(2) t1,t2 Each has a var => internal There is no lock contention problem
var slot = Thread.AllocateDataSlot("username");
// Set the slot on the main thread , in other words hello word Can only be read by the main thread , Other threads cannot read
Thread.SetData(slot, "hello word!!");
new Thread(() =>
{
Thread.SetData(slot, "hello!!");
var obj = Thread.GetData(slot);
Console.WriteLine(" Sub thread :{0}",obj);
}).Start();
var obj2 = Thread.GetData(slot);
Console.WriteLine(" The main thread :{0}",obj2);
Console.ReadKey();
Output results : Belong to the situation (2)
Performance enhanced version :ThreadStatic
[ThreadStatic]
static string username = "??!!";
static void Main(string[] args)
{
username = "hello word!!";
new Thread(() =>
{
username = "hello!!";
Console.WriteLine(" Sub thread :{0}", username);
}).Start();
Console.WriteLine(" The main thread :{0}", username);
Console.ReadKey();
}
Running results : Belong to the situation (2)
ThreadLocal: Also called thread visibility
ThreadLocal<string> local = new ThreadLocal<string>();
local.Value = "hello word!!";
new Thread(() =>
{
local.Value = "hello!!";
Console.WriteLine(" Sub thread :{0}", local.Value);
}).Start();
Console.WriteLine(" The main thread :{0}", local.Value);
Console.ReadKey();
Running results : Belong to the situation (2)
summary
These data are stored in the thread environment , Is the space overhead of the thread .
Memory fence
release and debug The difference in performance
In actual projects , The release versions are release edition , instead of debug edition , because release Some code and cache optimizations have been done in , For example, some data from memory Read in the CPU In cache . This operation may bring some bug.
The following code is in release There is a problem that the main thread cannot end execution in the environment .
var isStop = false;
Thread t = new Thread(() =>
{
var isSuccess = false;
while (!isStop)
{
isSuccess = !isSuccess;
}
});
t.Start();
Thread.Sleep(1000);
isStop = true;
t.Join();
Console.WriteLine(" End of main thread execution ");
Console.ReadKey();
From the code, it can be found that two threads are sharing one isStop Variable , And threads t This variable will be loaded into CPU Cache in , When the main thread pair isStop After modification , Threads t Can't perceive .
Two solutions :
1. Don't let multiple threads operate on a shared variable , Otherwise, it is easy to have problems .
2. If it has to be done , You do not need to cache , Every time from memory Read data from .
MemoryBarrier and VolatileRead
All memory writes prior to this method should be made from CPU Cache Update to memory, All memory reads after this method are from memory Read in instead of CPU Cache.
MemoryBarrier:
var isStop = false;
Thread t = new Thread(() =>
{
var isSuccess = false;
while (!isStop)
{
Thread.MemoryBarrier();
isSuccess = !isSuccess;
}
});
t.Start();
Thread.Sleep(1000);
isStop = true;
t.Join();
Console.WriteLine(" End of main thread execution ");
Console.ReadKey();
VolatileRead:
var isStop = 0;
Thread t = new Thread(() =>
{
var isSuccess = false;
while (isStop != 1)
{
Thread.VolatileRead(ref isStop);
isSuccess = !isSuccess;
}
});
t.Start();
Thread.Sleep(1000);
isStop = 1;
t.Join();
Console.WriteLine(" End of main thread execution ");
Console.ReadKey();
边栏推荐
- 【解决】每次加载已经训练好的模型,生成的向量会有不同
- Talk about message oriented middleware (1) and AMQP
- [FAQ] résumé des problèmes courants et des solutions lors de l'utilisation de l'interface API rest du Service de santé sportive
- MarkDown 标题居中
- [operation tutorial] how to correctly use the Hikvision demo tool to configure the channel to go online?
- Pycharm安装详细教程
- Cardview usage and properties
- Bottomnavigationview is used in conjunction with viewpager, to modify icon size, to remove text, etc
- [raise bar C #] how to call the base of the interface
- [note] about the problem of insufficient compilation mapping memory in keil
猜你喜欢
随机推荐
Leetcode-57- insert interval
Implementation of VGA protocol based on FPGA
What can the graph of training and verification indicators tell us in machine learning?
Markdown Title centered
Notes - simple but adequate series_ The Yapi return parameter data should be an object type problem solving record
Use of 5.8G microwave radar module, working principle and introduction of 5.8G microwave radar module
自适应功能简略
《软件体系结构原理、方法与实践》第二版期末考试复习总结
Recyclerview multi layout writing method, "my" and "personal center" page classic writing method demonstration
多云管理平台cmp是什么意思?谁能清楚解释一下
[note] the environment for setting up get injectedthread script supplemented by shellcode in Windows Security III and its use
NC|王军/宋默识结合三代测序解析肠道菌群结构变异和功能
新功能|Mail GPU Counter模块新增GPU图元处理和GPU Shader Cycles
c#浅拷贝与深拷贝自定义的类的List<>
【无标题】
【专题介绍】圆桌论坛——AI与音视频技术的融合之路
[notes] notes on C language array pointer, structure + two-dimensional array pointer
Flutter 页面跳转 传参,TabBar学习总结5
【深度学习05】 交叉熵损失函数
What are the common automated test frameworks? Shanghai software testing company Amway






![[note] about the problem of insufficient compilation mapping memory in keil](/img/0d/789c7629823600dbc77e62744ef5a1.png)
![buuctf [PHP]CVE-2019-11043](/img/ba/d97fe48acfd20daa66d47f34d99cf1.png)

![buuctf [Jupyter]notebook-rce](/img/fc/9c2047bdadb606b555e48f553fb1dd.png)