变量作为 pthreads 中的参数 [英] variable as argument in pthreads

查看:65
本文介绍了变量作为 pthreads 中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个用于创建线程数的程序.该数字可以作为命令行参数传递或默认值为 5.我面临的问题是打印作为参数传递给 pthread writer 函数的线程编号.

I have written a program for creating number of threads. The number can be passed as a command line argument or default value is 5. The problem I am facing is printing the thread number passed as an argument to pthread writer function.

下面是我的程序:

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

void *writerThread(void *args)
{
  int id = *((int *)args);
  printf("In thread %d\n", id);
}

int main(int argc, char *argv[])
{
  int numThreads;
  if(argc != 2)
    numThreads = 5;
  else
    numThreads = atoi(argv[1]);

  pthread_t *tId = (pthread_t*) malloc(sizeof(pthread_t) * numThreads);

  int i;
  for(i = 0; i < numThreads; i++)
  {
    pthread_create(&tId[i], NULL , writerThread, &i);
  }

  // wait for threads
  for(i = 0; i < numThreads; i++)
    pthread_join(tId[i], NULL);

  if(tId)
    free(tId);

  return 0;
}

输出:

In thread 2
In thread 0
In thread 3
In thread 2
In thread 0

为什么 0 和 2 来了两次?任何帮助将不胜感激.

Why 0 and 2 are coming two times ? Any help would be appreciated.

推荐答案

创建线程时

pthread_create(&tId[i], NULL , writerThread, &i);

i 继续它的生命......因此,当您在线程中打印 *(int*)args 时.您将获得 i 的当前值,该值在 main 函数中不断被使用和更改.

i continues its life... thus when you print *(int*)args in the thread. you get the current value ofi that keeps being used and changed in the main function.

您可能希望分配一个包含线程 id 的整数数组,并在线程创建期间存储该 id

You might want to allocate an array of integers that contain the thread id and store the id during the thread creation

int tids[numThreads];
for(i = 0; i < numThreads; i++) {
   tids[i] = i;
   pthread_create(&tId[i], NULL , writerThread, &tids[i]);
}

这样,每个线程都有一个参数指向自己的个人数据(在这种情况下,是一个整数).

This way, each thread has an argument that points to its own personal data (in that case, an integer).

这篇关于变量作为 pthreads 中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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