c - 如何通过访问其内存地址将局部变量从一个线程传递到另一个线程?
问题描述
我试图通过从其内存地址访问它来用函数TaskCode中作为参数的值覆盖数组中下一项的值。我尝试了很多组合,但它并没有像我预期的那样工作。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define NUM_THREADS 5
void* TaskCode(void* argument) {
int tid = *((int*)argument); //set tid to value of thread
tid++; // go to next memory address of thread_args
tid = *((int*)argument); // set that value to the value of argument
printf("\nI have the value: \" %d \" and address: %p! \n", tid, &tid);
return NULL;
}
int main(int argc, char* argv[])
{
pthread_t threads[NUM_THREADS]; // array of 5 threads
int thread_args[NUM_THREADS +1 ]; // array of 6 integers
int rc, i;
for (i = 0; i < NUM_THREADS; ++i) {/* create all threads */
thread_args[i] = i; // set the value thread_args[i] to 0,1...,4
printf("In main: creating thread %d\n", i);
rc = pthread_create(&threads[i], NULL, TaskCode,
(void*)&thread_args[i]);
assert(0 == rc);
}
/* wait for all threads to complete */
for (i = 0; i < NUM_THREADS; ++i) {
rc = pthread_join(threads[i], NULL);
assert(0 == rc);
}
exit(EXIT_SUCCESS);
}
解决方案
在您的线程函数中,tid
是数组中特定成员的值。对此变量的任何更改都不会反映在其他地方。thread_args
main
与其立即取消引用转换后的参数,不如直接将其作为int *
. 然后您可以对其进行指针运算并进一步取消引用它。
void* TaskCode(void* argument) {
int *tid = argument;
tid++;
*tid = *((int*)argument);
printf("\nI have the value: \" %d \" and address: %p! \n", *tid, (void *)tid);
return NULL;
}
推荐阅读
- substrate - 如何在 Substrate 中安装四个节点的网络
- angular - Angular 组件不会对属性更改做出反应
- ios - 离子(Appflow):请注册自定义 URL 方案 - 方案存在于 plist 文件中
- haskell - Control.Lens 中的 Market 名称背后的原因是什么?
- python - 改组数据框中的多列
- function - Sharepoint 如何更改新文档的功能
- javascript - Jest 模拟不适用于 react-native 输入
- javascript - Vue JS:同时获取输入数组的唯一ID和值
- uwp - 如何使用 UWP Backbround Task 从本地存储(比如 "C:\\" )读取文件?
- javascript - React 中通过 ID 访问 DOM 元素