gpt4 book ai didi

c++ - 我们如何知道代码是线程安全的?

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:08 25 4
gpt4 key购买 nike

我正在关注 this tutorial了解如何删除锁,使用 VTUNE
该页面在收集 Vtune 结果后说了以下内容:

识别 HitTest 门的代码行

Click the hotspot navigation button to go to the code line that took the most Wait time. VTune Amplifier highlights line 170 entering the critical section rgb_critical_section in the draw_task function. The draw_task function was waiting for almost 27 seconds while this code line was executing and most of the time the processor was underutilized. During this time, the critical section was contended 438 times.

The rgb_critical section is the place where the application is serializing. Each thread has to wait for the critical section to be available before it can proceed. Only one thread can be in the critical section at a time. You need to optimize the code to make it more concurrent.

在到达下一节之前,我能够按照本教程进行操作:Remove the Lock

解除锁定

The rgb_critical_section was introduced to protect calculation from multithreaded access. The brief analysis shows that the code is thread safe and the critical section is not really needed.

我的问题是我们如何知道代码是线程安全的?

正如我建议的那样,我对这些行(EnterCritical... 和 LeaveCritical...)进行了评论,并看到了巨大的性能提升,但我不明白为什么不需要这个关键部分?哪个分析告诉我们这一点?

相关代码在analyze_locks.cpp中:

public:
void operator () (const tbb::blocked_range <int> &r) const {

unsigned int serial = 1;
unsigned int mboxsize = sizeof(unsigned int)*(max_objectid() + 20);
unsigned int * local_mbox = (unsigned int *) alloca(mboxsize);
memset(local_mbox,0,mboxsize);

for (int y=r.begin(); y!=r.end(); ++y) {
drawing_area drawing(startx, totaly-y, stopx-startx, 1);

// Enter Critical Section to protect pixel calculation from multithreaded access (Needed?)
// EnterCriticalSection(&rgb_critical_section);

for (int x = startx; x < stopx; x++) {
color_t c = render_one_pixel (x, y, local_mbox, serial, startx, stopx, starty, stopy);
drawing.put_pixel(c);
}

// Exit from the critical section
// LeaveCriticalSection(&rgb_critical_section);

if(!video->next_frame()) tbb::task::self().cancel_group_execution();
}
}

draw_task () {}

};

最佳答案

如果没有修改全局状态(即此特定线程之外的状态),则某些内容是线程安全的。我们很难说出 render_one_pixeldrawing.put_pixel 实际做了什么,以及它们可能需要以什么顺序执行。

假设调用 put_pixel(c) 的顺序无关紧要(或者哪个线程进行调用),那么删除这里的临界区是安全的。如果需要严格的排序,我不确定关键部分是否是正确的解决方案。 (同样的规则显然适用于 render_one_pixel,如果它改变了一些全局状态,这当然也必须在“是否安全”中考虑)。

关于c++ - 我们如何知道代码是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com