Chi*_*eno 1 c++ windows multithreading
我有问题访问和修改我的多线程数据.有没有正确的方法来做到这一点?
这是我的完整代码:
#include <stdio.h>
#include <windows.h>
// Create thread data structure
struct data
{
int a;
float b;
char *c;
};
DWORD WINAPI threadfn(LPVOID lpParam)
{
printf("Address of thread data:\n");
for(int i=0; i<sizeof(lpParam); i++)
printf("%X\n", (int*)lpParam + i);
// Print out initial values
printf("\nInitial values:\n");
printf("a: %d\n", *((int*)lpParam));
printf("b: %.2f\n", *((float*)lpParam + 1));
printf("c: %s\n", *((int*)lpParam + 2));
// Modify thread data values
*(int*)lpParam = 200;
*((float*)lpParam + 1) = 25.80;
*((char*)lpParam + 2) = "Es la una";
return 0;
}
int main()
{
HANDLE hThread;
data thread;
// Set initial thread data values
thread.a = 10; // Integer data type
thread.b = 15.60; // Float data type
thread.c = "Que hora es?"; // String data type
hThread = CreateThread(NULL, 0, threadfn, &thread, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
// Print out thread value after modification
printf("\nAfter thread modifications:\n");
printf("a: %d\n", thread.a);
printf("b: %.2f\n", thread.b);
printf("c: %s\n", thread.c);
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
Address of thread data:
28FF20
28FF24
28FF28
28FF2C
Initial values:
a: 10
b: 15.60
c: Que hora es?
After thread modifications:
a: 7405768
b: 25.80
c: Que hora es?
Run Code Online (Sandbox Code Playgroud)
如您所见,'c'值相同.我如何修改字符串值?
你到底在做什么?!所有lpData的强制转换都非常非常错误.如果你必须做那么多的铸造来完成某些事情,你可能没有以正确的方式做到这一点.
无论如何,您的代码应如下所示:
DWORD WINAPI threadfn(LPVOID lpParam)
{
printf("Address of thread data:\n");
data *lpData = (data *)(lpParam);
for(int i=0; i<sizeof(lpParam); i++)
printf("%X\n", (int*)lpParam + i);
// Print out initial values
printf("\nInitial values:\n");
printf("a: %d\n", lpData->a);
printf("b: %.2f\n", lpData->b);
printf("c: %s\n", lpData->c);
// Modify thread data values
lpData->a = 200;
lpData->b = 25.80;
lpData->c = "Es la una";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你应该使用(data *)(lpParam)
它,因为它基本上会逆转你打电话时发生的事情CreateThread
.就个人而言,认为P
类型名称的愚蠢符号更多是一种阻碍,而不是一种帮助,因为它模糊了实际发生的事情. 匈牙利表示法一般有这个问题恕我直言.
在您的main
函数中,您有以下代码:
hThread = CreateThread(NULL, 0, threadfn, &thread, 0, NULL);
Run Code Online (Sandbox Code Playgroud)
第四个参数CreateThread
是a void *
(又名a PVOID
).表达式的类型&thread
是data *
.这意味着它data *
被隐式转换为a void *
.如果您明确地进行转换,则代码如下所示:
hThread = CreateThread(NULL, 0, threadfn, (void *)(&thread), 0, NULL);
Run Code Online (Sandbox Code Playgroud)
因此,为了"撤消"所做的事情,你需要"反转"演员表.您需要将void *
后面变成一个data *
,这意味着threadfn
需要代码data *lpData = (data *)(lpParam);
.
此外,您通过设置c
指向常量字符串来追求灾难,因为您没有将其声明为const char *
.我很惊讶编译器没有给你一个错误.当你做类似的事情时,就会发生灾难data.c[0] = 'f';
.当你这样做时,你将尝试修改可能被标记为只读的内存并导致程序崩溃.这是可能发生的最好的事情.
归档时间: |
|
查看次数: |
695 次 |
最近记录: |