编写的dll如下所示:
#include<stdio.h>#pragma data_seg("MySec")
int m=3;
#pragma data_seg()#pragma comment(linker,"/section:MySec,RWS")void change(int x)
{
m=x;
printf("m=%d\n",m);
}void print()
{
printf("this is :m=%d\n",m);
}
然后在测试程序中,创建两个线程:
#include<stdio.h>
#include<iostream.h>
#include<windows.h>
_declspec(dllimport) void change(int x);
_declspec(dllimport) void print();
DWORD WINAPI ThreadProc1(
LPVOID lpParameter)
{
change(4);
print();
return 0;};
DWORD WINAPI ThreadProc2(
LPVOID lpParameter)
{
Sleep(15);
print();
return 0;
};void main()
{
HANDLE hThread1;
HANDLE hThread2;
LPVOID lpParameter; hThread1=CreateThread(
NULL, // SD
0, // initial stack size
ThreadProc1, // thread function
(LPVOID)lpParameter, // thread argument
0, // creation option
NULL // thread identifier
);
hThread2=CreateThread(
NULL, // SD
0, // initial stack size
ThreadProc2, // thread function
(LPVOID)lpParameter, // thread argument
0, // creation option
NULL // thread identifier
);
Sleep(1000);
}为什么结果总是4呢? 并且将dll中没有设置新的数据段时,结果是一样的啊;
也就是说,我的第一个线程修改了全局变量m的值,然而第二个线程访问时,总是访问的修改后的m值;
可是相关资料中,系统存在写入时拷贝机制,这为什么不行呢? 盼高手指点……
#include<stdio.h>#pragma data_seg("MySec")
int m=3;
#pragma data_seg()#pragma comment(linker,"/section:MySec,RWS")void change(int x)
{
m=x;
printf("m=%d\n",m);
}void print()
{
printf("this is :m=%d\n",m);
}
然后在测试程序中,创建两个线程:
#include<stdio.h>
#include<iostream.h>
#include<windows.h>
_declspec(dllimport) void change(int x);
_declspec(dllimport) void print();
DWORD WINAPI ThreadProc1(
LPVOID lpParameter)
{
change(4);
print();
return 0;};
DWORD WINAPI ThreadProc2(
LPVOID lpParameter)
{
Sleep(15);
print();
return 0;
};void main()
{
HANDLE hThread1;
HANDLE hThread2;
LPVOID lpParameter; hThread1=CreateThread(
NULL, // SD
0, // initial stack size
ThreadProc1, // thread function
(LPVOID)lpParameter, // thread argument
0, // creation option
NULL // thread identifier
);
hThread2=CreateThread(
NULL, // SD
0, // initial stack size
ThreadProc2, // thread function
(LPVOID)lpParameter, // thread argument
0, // creation option
NULL // thread identifier
);
Sleep(1000);
}为什么结果总是4呢? 并且将dll中没有设置新的数据段时,结果是一样的啊;
也就是说,我的第一个线程修改了全局变量m的值,然而第二个线程访问时,总是访问的修改后的m值;
可是相关资料中,系统存在写入时拷贝机制,这为什么不行呢? 盼高手指点……
int m=3;
#pragma data_seg()
改下;int m=3; 就行了;
你的写法是数据段共享;
#pragma data_seg("MySec")
int m=3;
#pragma data_seg() 改成 int m=3;时 结果是一样的(都是4 4 4),即不存在共享数据段的意义了,
所以没有写出动态加载方法 还有 这好像跟问题 没什么关系……
谢谢
对啊
我也在想那个 “写入时拷贝”机制 只适用于不同进程调用同一dll??而不同线程调用 不存在这个机制?