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