简体   繁体   English

Posix线程参数问题(C)

[英]Posix thread arguments issue ( C )

I'm running into a bit of trouble with C. I'm a relatively new programmer and I'm trying to create a structure and pass it into two thread by reference. 我在使用C时遇到了一些麻烦。我是一个相对较新的程序员,我试图创建一个结构并将其通过引用传递给两个线程。 I want one thread to put information into the structure and the other thread to add the information and print it out. 我希望一个线程将信息放入结构中,而另一个线程将信息添加并打印出来。 Pseudo-code of what I'm talking about is below: 我在说什么的伪代码如下:

typedef struct{ int x, y }addme;
main{
  addme argstopass;
  create_thread(method_store, (void*)&argstopass);
  create_thread(method_calc, (void*)&argstopass);
  //Code to tell store thread 'only' to run
  //Code to tell calc thread to run when store is finished.
  join_both_threads;
}

void method_store(void* args){
  addme info = *((addme*)args);
  info.a = 7;
  info.b = 3;
}  

void method_calc(void* args){
  addme info = *((addme*)args);
  print(info.a+info.b);
}

The issue is that when I try to add the information it's like the store method had never updated it. 问题是,当我尝试添加信息时,就像store方法从未更新过它。 The reference passed into the threads is the same, so I can't see why they wouldn't be able to access the same information as long as they both have a pointer to it. 传递给线程的引用是相同的,因此我无法理解为什么只要它们都有指向它的指针,它们就无法访问相同的信息。

Hopefully someone here can enlighten me as to what I'm doing wrong. 希望这里有人可以启发我我做错了什么。 If anything isn't clear, comment and I'll help to clarify. 如果不清楚,请发表评论,我会帮助您澄清。

addme info = *((addme*)args);

creates a locale variable on stack and copies content of argstopass into it. 在堆栈上创建一个语言环境变量,并将argstopass内容argstopass到其中。 Modifications happen on this local variable only and won't be seen by the second thread hence. 修改仅在此局部变量上发生,因此第二个线程将看不到。

Use 采用

addme *info = args;
info->a = 7;

and ditto for the second thread. 和第二个线程同上。 You will have to ensure that second thread waits with its printf() until first thread modified the values. 您将必须确保第二个线程等待其printf()直到第一个线程修改了值。

void method_store(void* args){
  addme info = *((addme*)args);
  info.a = 7;
  info.b = 3;
}  

This method creates a local copy of your structure field, updates that local copy, and then returns, destroying the copy and not doing anything to your main structure. 此方法创建您的结构字段的本地副本,更新该本地副本,然后返回,销毁该副本并且不对您的主结构执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM