Reputation: 129
I have some difficulties in understanding multiple thread. Here is the situation:
I am going to select some integers from an array and store them into another array with some conditions. The conditions is quite complicated, basically it's a huge set of comparison between array[i] and all others array[not i]. Let's called it checkCondition();
First, I create the pthread. Here is my code, noted that dataPackage is a struct containing the array.
for(int i = 0; i < thread_number; i++){
if(pthread_create(&tid, NULL, checkPermissible, &dataPackage) != 0){
perror("Error occurs when creating thread!!!\n");
exit(EXIT_FAILURE);
}
}
for(int i = 0; i < thread_number; i++){
pthread_join(tid, NULL);
}
Here is the content of checkPermissible()
void* checkPermissible(void* content){
readThread *dataPackage = content;
for(int i = 0; i < (*dataPackage).arrayLength; i++){
if(checkCondition()){
pthread_mutex_lock(&mutex);
insert(array[i], (*dataPackage).result);
pthread_mutex_unlock(&mutex);
//if condition true, insert it into result(a pointer)
//mutex avoid different thread insert the value at the same time
}
}
pthread_exit(NULL);
}
However, It would not have any difference if I'm not using pThread way to do this. How to I implement checkPermissible() in order to bring out the advantage of multiple thread? I quite confused about this stuff.
My idea is, dividing the array into noOfThread in each Thread. For example, I have an array[20] and 4 thread,
Thread 1: compute checkCondition with array[0] to array[4]
Thread 2: compute checkCondition with array[5] to array[9]
Thread 3: compute checkCondition with array[10] to array[14]
Thread 4: compute checkCondition with array[15] to array[19]
Something like that, in which I don't know how to achieve.
Upvotes: 0
Views: 303
Reputation: 9415
First, you can pass lower and upper bound or addresses to a thread in your structure as follows:
struct readThread {
int low;
int hi;
int * myarray;
};
for (int i=low;i<hi;++i)
//or
struct readThread {
int * start;
int * end;
};
for (int* i=start; i<end; ++i)
First one is easier and easier to understand as well. In this way, your array will split.
There are other ways like creating split copies of your error for each thread.
Upvotes: 1