When I'm creating T threads, I have the following code in the main thread.
pthread_t threads[T];
for (a=0; a<T; a++) {
pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
}
printf("in main thread\n");
It creates the first thread, and I noticed that it immediately begins executing the first thread. foo is called for the first thread and "in main thread" gets outputed after. My actual intent was to create all T threads first (pushing the threads into a 'ready' queue) and then continue executing code in the main thread until it exits or yields. Once main exits, I want one of the T threads to execute.
In foo function:
void foo(pthread_t *threads, pthread_mutex_t **locks, double **transition) {
printf("in foo\n");
}
In the main_thread function:
void main_thread (int *N, int *T) {
double **transition;
pthread_mutex_t **locks;
transition = malloc(*N * sizeof *transition);
locks = malloc(*N * sizeof *locks);
for (a=0; a< *N; a++) {
transition[a] = malloc(*N * sizeof *transition[a]);
locks[a] = malloc(*N * sizeof *locks[a]);
}
// lock for each element in transition matrix
for (a=0; a<*N; a++) {
for (b=0; b<*N; b++) {
if (pthread_mutex_init(&(locks[a][b]), NULL) != 0) {
printf("\n mutex init has failed\n");
}
}
}
for (a=0; a<*N; a++) {
for (b=0; b<*N; b++) {
transition[a][b] = 0.0;
}
}
pthread_t threads[T];
for (a=0; a<T; a++) {
pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
}
printf("in main thread\n");
}
In the main function:
int main(int argc, char *argv[]) {
int N = 4;
int T = 2;
pthread_t main_t;
pthread_create(&main_t, NULL, &main_thread(&N, &T), NULL);
return 0;
}