为什么主线程被卡在pthread_create()案例中?
查看此代码时,有人指出主线程可能会被卡住而无法完成主要功能: 代码
int count = numthreads; void* bar(void* arg){ / *做一些事情 */ - 数数; } int main(int argc,char* argv []){ / * ...初始化所有内容... */ for(i = 0; i< numthreads; ++ i) pthread_create(& thread [i],null,bar,null); 而(count> 0) 睡眠(1); }
上述代码正确吗?
(א)是。 (ב)是的,如果在运行期间没有信号发送到该过程。 (ג)不,主线程可能无法完成。 (ד)不,主线程可能在所有[其他]线程完成之前完成。
如果bar()没有无限循环,怎么会卡住?
When looking at this code someone noted that the main thread might get stuck and not finish the main function :
the code
int count = numThreads; void* bar(void* arg) { /* do some stuff */ --count; } int main(int argc, char* argv[]) { /* ... initialize everything ... */ for (i = 0 ; i < numThreads; ++i) pthread_create(&thread[i],NULL,bar,NULL); while (count > 0) sleep(1); }
Is the above code correct?
(א) Yes. (ב) Yes if no signals are sent to the process during the run. (ג) No, the main thread may not finish. (ד) No, the main thread may finish before all the [other] threads finish.
How come it gets stuck if the bar() has no infinite loops?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ג和ד都是正确的答案。该代码具有a data Race ,因为非原子量变量
Count
与其他访问同时编写,而无需静音或任何其他同步。因此,根据C标准,其行为不确定。它可能以任何其他可以想象的方式早期完成,或者根本没有完成,或者崩溃或不良行为。要查看它可以永远循环的特定方式,请注意,由于
Count
不是 aromic 变量,减少- count
不是原子操作。因此,可以通过从内存中加载Count
的值,减去1并存储新值来实现它,并且这些访问可以交错。例如,我们可以具有以下事件的顺序:线程1从
count
中加载,获取值2线程1降低2,并确定其应存储新值1
螺纹2从
count
加载,获取值2线程2降低2,并确定它应该存储新值1
线程1将值1存储至
count
线程2将值1到
count
存储。
,然后两个线程完成。不会进一步写入
Count
,因此它将永远无法达到值0,并且main
中的循环永远不会退出。Both ג and ד are correct answers. This code has a data race, because the non-atomic variable
count
is written concurrently with other accesses, without mutexes or any other synchronization. So according to the C standard, its behavior is undefined. It may finish early, or not finish at all, or crash, or misbehave in any other imaginable fashion.To see a particular way in which it could loop forever, note that since
count
is not an atomic variable, the decrement--count
is not an atomic operation. So it could be implemented by loading the value ofcount
from memory, subtracting 1, and storing the new value, and these accesses could be interleaved. For instance, we could have the following sequence of events:Thread 1 loads from
count
, getting the value 2Thread 1 decrements 2 and decides it should store the new value 1
Thread 2 loads from
count
, getting the value 2Thread 2 decrements 2 and decides it should store the new value 1
Thread 1 stores the value 1 to
count
Thread 2 stores the value 1 to
count
and then both threads finish. No further writes to
count
will occur, so it will never attain the value 0, and the loop inmain
will never exit.