将参数传递给 _beginthread() —— 有什么问题? [英] passing arguments to _beginthread() -- whats wrong?

查看:28
本文介绍了将参数传递给 _beginthread() —— 有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,但没有得到预期的结果……怎么了?

I have this code and I am not getting the expected results... whats wrong?

typedef struct {
   int data1;
   int data2;
}t;

void foo(int a, int b) {

   Handle handle;
   t arg;
   arg.data1 = a;
   arg.data2 = b;
   handle = (HANDLE) _beginthread( myFunc, 0, (void*) &arg);
}

void myFunc(void *param) {
   t *args = (t*) param;
   int x = args->data1;
   int y = args->data2;
   printf("x=%d, y=%d\n", x, y);
} 

推荐答案

arg 是定义在 foo 中的局部变量 - 一旦该函数结束它就会被销毁,但是在另一个线程中运行的 myFunc 仍然会尝试访问它.您应该在堆上分配 arg 并在完成后在线程中销毁它.

arg is a local variable defined in foo - it would be destroyed as soon as that function ends, but myFunc which is running in another thread would still be trying to access it. You should allocate arg on the heap and destroy it in the thread after you are done.

void foo(int a, int b) {
   HANDLE handle;
   t *arg;
   arg = (t *)malloc(sizeof(t));
   arg->data1 = a;
   arg->data2 = b;
   handle = (HANDLE) _beginthread( myFunc, 0, (void*) arg);
}

void myFunc(void *param) {
   t *args = (t*) param;
   int x = args->data1;
   int y = args->data2;
   printf("x=%d, y=%d\n", x, y);
   free(args);
}

还要注意 HANDLE 应该全部大写.

Also note that HANDLE should be all caps.

这篇关于将参数传递给 _beginthread() —— 有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆