传递参数给_beginthread() - 什么是错? [英] passing arguments to _beginthread() -- whats wrong?

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

问题描述

我有这样的code,我没有得到预期的结果...什么错?

  typedef结构{
   INT DATA1;
   INT数据2;
}吨;无效美孚(INT A,INT B){   提手;
   ŤARG;
   arg.data1 =一个;
   arg.data2 = B;
   处理=(HANDLE)_beginthread(myFunc的,0,(无效*)及ARG);
}无效myFunc的(无效*参数){
   T * ARGS =(T *)参数;
   INT X = args-> DATA1;
   INT Y = args->数据2;
   的printf(X =%D,Y =%d个\\ N,X,Y);
}


解决方案

ARG 富 - 这将尽快那个函数结束,但 myFunc的这是在另一个线程中运行仍然会试图访问它被销毁。您应该分配 ARG 在堆上,并摧毁它的线程在完成后。

 无效美孚(INT A,INT B){
   提手;
   T * ARG;
   ARG =(T *)malloc的(的sizeof(T));
   arg->数据1 =一;
   arg->数据2 = B;
   处理=(HANDLE)_beginthread(myFunc的,0,(无效*)ARG);
}无效myFunc的(无效*参数){
   T * ARGS =(T *)参数;
   INT X = args-> DATA1;
   INT Y = args->数据2;
   的printf(X =%D,Y =%d个\\ N,X,Y);
   免费(参数);
}

另外请注意, HANDLE 应该是全部大写。

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 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);
}

Also note that HANDLE should be all caps.

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

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