Does using locals as arguments in pthread_create() work?

自古美人都是妖i 提交于 2021-02-10 20:14:05

问题


This is mainly a question about scope and threads. Let's say we have the following struct.

struct Test
{
  int number;
  std::string name;
};

An instance of this struct will be used as an argument in the pthread_create function. Here is an example of what this might look like.

pthread_t tid[5];
for(int i = 0; i < 5; ++i)
{
  Test test;
  test.number = 5;
  test.name = "test";
  pthread_create(&tid[i], NULL, func, (void *)&test);
}

Is this acceptable? Since test is declared in the for's scope, that means we can only rely on it existing during a single iteration of the for loop.

When pthread_create is called, a pointer to test is given as an argument. This means that func is receiving the same pointer that is passed in to pthread_create. This means that when test goes out of scope, we can no longer rely on that pointer referring to test. If we were to create more locals, hence changing the stack, the location that the pointer points to would be overwritten by those new locals. Is this correct?


回答1:


Is this acceptable?

In general, no, for the reasons you stated. Specifically, the thread's entry-function may not start executing until after the Test object has been destroyed, or the Test object might be destroyed while the thread's entry-function is still using it. Either of those possibilities will lead to undefined behavior (and a program that only works correctly "sometimes").

You need to guarantee that the data you pass to the thread remains valid for as long as the thread needs to use it. One way to do that is to allocate that Test object on the heap, and have the thread call delete on the Test-pointer when it's done using it. Alternatively, you could use a condition variable to "pause" the main thread until the child pthread signals that it is done accessing the Test on the main thread's stack, so that it is now safe for the main thread to continue execution.

If we were to create more locals, hence changing the stack, the location that the pointer points to would be overwritten by those new locals. Is this correct?

Yes, you understand the issue correctly.



来源:https://stackoverflow.com/questions/48555870/does-using-locals-as-arguments-in-pthread-create-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!