pthread_create传递参数

时间:2016-11-13 06:42:48

标签: c pthreads

这段代码有什么问题?在function()中,偏移值打印为-1。我希望它是值10-1的偏移量为sum = -1000注意:offset存储在堆内存中。

test()打印预期输出。

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

pthread_t thread[2];
int sum = 0;

void*
function(void *arg){
   int i;
   int offset = *((int *)arg);
   printf("offset = %d \n",*(int *)arg);
   for(i=0;i<1000;i++){
      sum = sum+offset;
   }
   printf("\n sum = %d \n",sum);
   pthread_exit(NULL);
}

void test(void* val){
   int offset = *((int *)val);
   printf("Inside test function.offset = %d \n",offset);
}

int main(){
   int ret;
   int *offset = (int *)malloc(sizeof(int));

   *offset = 10;
   test(offset);

   ret = pthread_create(&thread[0], NULL, &function,(void *)offset);
   if(ret!=0)
      printf("pthread create error \n");

   pthread_join(thread[0],NULL);

   return 0;
}

输出:

Inside test function.offset = 10
offset = -1
sum = -1000

测试平台:Ubuntu 14.04 LTS,GCC 4.8.4,Linux内核3.13.0-57-generic。

gdb输出:

Breakpoint 1, function (arg=0x7fffffffdd4c) at mutex_lock.c:11
11         int offset = *((int *)arg);
(gdb) p *((int *)arg)
$4 = -1

0 个答案:

没有答案