[英]Can't pthreads access variables from the main() function?
int main()
{
int i;
pthread_t t;
}
Can t not see i? 看不到我吗? t is created inside main, right? t是在main内部创建的,对吗? That means it must be using the same shared memory main() is using? 这意味着它必须使用main()正在使用的相同共享内存? How do I make it see i without making ia global variable? 我如何在不使ia为全局变量的情况下看到i?
What? 什么? t
is a thread, it doesn't really "see" anything. t
是一个线程,它实际上并没有“看到”任何东西。 Strictly, it's a variable that represents a thread -- you haven't actually created a thread -- but assuming you do create one, it runs in the same process as main()
, so it shares memory space in that sense, but it doesn't share the scope of main. 严格来说,它是一个代表线程的变量-您实际上并未创建线程-但假设您确实创建了一个线程,它与main()
运行过程相同,因此从某种意义上讲它共享内存空间,但是不共享main的范围。 The functions which run in that thread can see whatever variables are in scope for those functions. 在该线程中运行的函数可以查看这些函数范围内的任何变量。
You could pass a pointer to i
as the user data pointer to pthread_create
. 您可以将指向i
的指针作为指向pthread_create
的用户数据指针。 Or if you need to access more than just i
, you could pass a pointer to some structure which contains (among other things) a pointer to i
, and so on. 或者,如果您需要访问的不仅仅是i
,则可以传递指向某个结构的指针,该结构包含(除其他事项外)指向i
的指针,依此类推。
Example code: 示例代码:
#include <pthread.h>
#include <iostream>
#include <cstring>
void *thread_entry_point(void *data) {
int *idata = static_cast<int*>(data);
std::cout << "thread: i = " << *idata << "\n";
*idata = 23;
return const_cast<char*>("might as well return something");
}
int main() {
int i = 12;
pthread_t thr;
int err = pthread_create(&thr, 0, thread_entry_point, &i);
if (err == 0) {
void *result;
pthread_join(thr, &result);
std::cout << "main: result = " << static_cast<const char*>(result) << "\n";
std::cout << "main: i = " << i << "\n";
} else {
std::cout << "error creating thread: " << err << " " << std::strerror(err) << "\n";
}
}
pthreads aren't special. pthread并不特殊。 For instance, the following code has the same "problem": 例如,以下代码具有相同的“问题”:
void foo()
{
i = 5;
}
int main()
{
int i;
foo();
}
Surely foo
is called by main
, so they're even on the same thread. 当然foo
是由main
调用的,因此它们甚至在同一线程上。 Yet foo
doesn't see the int
in main
. 但是foo
在main
中看不到int
。 The solution is simple: if foo
needs an int
, main
should pass that: 解决方案很简单:如果foo
需要一个int
, main
应该通过:
void foo(int& i)
{
i = 5;
}
int main()
{
int i;
foo(i);
}
With threads, the situation is the same: pass what you need to share. 使用线程,情况是一样的:传递您需要共享的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.