I have some issue with passing an element of an array through pthread_create as paramenter.
I have this struct:
struct threadInfo {
int threadNumber;
int sleepTime;
};
I initialize the array (in a function) like this:
struct threadInfo info[1];
Then in a while-loop I do this:
int i = 0;
...
while (i < 2) {
pthread_mutex_lock(&countMutex);
if (threadsCount < MAX_THREAD) {
info[i].threadNumber = ++threadsCount;
pthread_mutex_unlock(&countMutex);
info[i].sleepTime = rand() % (10 + 1 - 1) + 1;
pthread_create(&threads[i], NULL, lawine, &info[i]);
i++;
}
else {
pthread_mutex_unlock(&countMutex);
break;
}
}
threadsCount is a global var.
In the first turn it works fine(info[0]). But In the second round (info1) the values are wrong. the output
Can you help me?
You're going out of bounds on your array as you've only declared it to hold one element, but you're expecting it to hold 2. The number inside the square brackets in this line of code...
struct threadInfo info[1];
... isn't the highest index you can access. It's the number of elements, so if you want to have 2 elements (and thus be able to access info[1]
) you need to allocate it like so:
struct threadInfo info[2];
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments