I have a range of number (i.e 1~10000).
I need to create threads
to search for a value X.
Each thread will have your own interval to search for it (i.e 10000/threadNumber).
I guess there is no meaning to make the threads run in sequence. I'm having problem to make they run concurrently...
My Code so far:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define limit 10000
#define n_threads 2
void* func1(void* arg)
{
int i=0, *value = (int *)arg;
//How may I know which thread is running and make the thread search for the right range of values ?
for(i=1; i<=limit/n_threads; i++)
{
if(*value == i){
//Print the thread ID and the value found.
}
else
//Print the thread ID and the value 0.
}
return NULL;
}
int main(int argc, char const *argv[])
{
if(argc < 2)
printf("Please, informe the value you want to search...\n");
else{
pthread_t t1, t2;
int x = atoi(argv[1]); //Value to search
pthread_create(&t1, NULL, func1, (void *)(&x));
pthread_create(&t2, NULL, func1, (void *)(&x));
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
return 0;
}
Problems so far:
- I don't know how to find
thread ID
. (tried withpthread_self()
but I always get a giant negaative number so I think something is wrong. - I know that
pthread_create()
creates and initialize the thread, also thepthread_join
will make my main program to wait for the thread. But Looking into my code it doesn't seems to be runing concurrently. How my
threadX
will know from what range of values it's suppose to start searching ? (i.e: If I have 10 threads, I don't think I'll have to create 10 functions o.O ).is it possible to make them run concurrently without something like
Mutex
?