Hi i called this pthreads questions even though ultimately it might not come down to just pthreads but something more general. I dunno.
In my C program i have the main function call a function that creates some pthreads. The program is a TCP/IP daemon that serves some basic text-based games like tic-tac-toe(yes this is just a programming exercise). Thus it is pre-threaded and each thread serves a game. So the main loop of the program happens in the code of each thread. However because the main loop of these basic games is now called in the thread code, instead of in main where it originally was, functions external to the thread have to get called from within the thread. The games state is a [3][3] char array which was global originally. So now because it's supposed to be a network daemon, i have to use "thread-specific-data" for this [3][3] char array. Here is the main loop from each thread:
Code:
void *thread_main()
{
char done = ' ';
init_matrix();
do {
disp_matrix();
get_player_move();
done = check();
if(done != ' ') break;
get_computer_move();
done = check();
} while(done == ' ');
if(done == 'X') printf("You Won\n");
else printf("I won\n");
disp_matrix();
freeaddrinfo(res);
return(0);
}
And here is the "thread-specific-data" for the games state([3][3] char array)created in "get_player_move"
Code:
pthread_once(&ts_once, pt_once);
if((tsd = pthread_getspecific(tskey)) == NULL) {
tsd = calloc(1, sizeof(Thread));
pthread_setspecific(tskey, tsd);
}
So now because the [3][3] char array for the games "state" is in the Thread struct pointed to by tsd then "struct Thread *tsd" has to be global as in the code example above! or has to be passed as an argument to each function.
Can you have a pointer to thread specific data(that gets returned from pthread_get_specific) declared as a global? And if not then how do you pass it to all the functions that the threads call?But if i pass "struct Thread *tsd" to the functions the compiler kicks out like 12 errors. The main one is "expected expression" with reference to functions like init_matrix. the call conforms to the prototype namely "init_matrix(struct Thread *tsd)".
I don't know how to fix this.
I'm really sorry that i haven't written about this in a general and concise way. I don't know if i understand C enough yet to do that. Any help would be great. Thank you very much for reading