且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问linux线程(pthreads)的本地堆栈

更新时间:2023-11-13 17:27:04

是的,正如您所解释的,您可以共享堆栈.但是,一般而言,除了少数特殊情况外,您不应该这样做.您的示例程序有数据争用,因此仅凭运气就只能输出200(也许是因为您的操作系统实际上并未安排子进程同时运行.)

Yes, you can share your stacks, as you explain. In general, however, you should not, except in a few special circumstances. Your example program has data races, and so the output will only be 200 through pure luck (perhaps because your operating system doesn't actually schedule the children to run simultaneously.)

共享堆栈很有意义的一种特殊情况是,父级创建一些有趣的数据结构,然后将其传递给其子级,后者访问该数据结构为只读.

One special circumstance where it does make sense to share the stack is when the parent creates some interesting data structure, and then passes it to its children, who access the data structure read only.

除了数据争用之外,还有另一件事可能是在堆栈而不是堆上共享.父级可以从创建子线程的过程中返回,因此堆栈数据在子线程的生存期内可能不会保持有效.因此,仅当pthread_create()调用和匹配的pthread_join()调用在同一范围内时才共享堆栈数据(如您的示例中一样).

Other than data races, here's another thing that can go wrong with sharing on the stack instead of the heap. The parent can return from the procedure where it created the child threads, so the stack data may not stay valid for the lifetime of the child thread. So you should only share stack data if the pthread_create() call and the matching pthread_join() call are in the same scope (as they are in your example.)