0

I am creating n threads. I would like to create n variables b1,b2,b3,.,bi,..bn. How can I do this in C? I mean to choose the name of the global variable according to the number of the thread.

thanks

nobody
  • 19,814
  • 17
  • 56
  • 77
user3242743
  • 1,751
  • 5
  • 22
  • 32
  • 4
    You can't. Variable names only exist at compile time, while threads only exist at runtime. As others have said, you can get a similar effect by using an array with one element per thread instead. – NapoleonBlownapart May 09 '14 at 07:20
  • 1
    http://stackoverflow.com/questions/6064873/dynamic-variable-declaration-in-c – Mat May 09 '14 at 07:20

2 Answers2

3

Taken from NapoleonBlownapart's comment to the OP: "You can't. Variable names only exist at compile time, while threads only exist at runtime."

Use an array, with as much elements as you have threads. Then use the thread's number as index to the arrary

See some pseudo code below:

#define THREAD_MAXIMUM (42)

int b[THREAD_MAXIMUM];


thread_func(void * pv)
{
  size_t i = (size_t) pv;

  int bi = b[i];
  ...
}

int main()
{
  ...

  for(size_t i = 0; i < THREAD_MAXIMUM; ++i)
  {
     b[i] = some thread specific number;
     create-thread(thread_func, i) /* create thread and pass index to array element);
  }

  ...
}
Community
  • 1
  • 1
alk
  • 69,737
  • 10
  • 105
  • 255
1

You can try with arrays or vectors(in C++). I would have preferred coding in C++ and use vector instead of C and array.

Simple implementation with array can be as follows -

#define MAX_THREAD(100)

int var[MAX_THREAD]

ThreadImpl(Params)
{
 int i = (int) Params;

 int vari = var[i];
}

int main()
{
  for(int i = 0; i < MAX_THREAD; ++i)
  {
    var[i] = val; (val can be ThreadID or other value as per requirement)     
    pthread_create(ThreadImpl, ... other params);
  }

 return 0;
}
Naseef Chowdhury
  • 2,357
  • 3
  • 28
  • 52