c - Close a socket from the main thread -
i'm implementing p2p file transfer peer , tracker. tracker keeps track of peers , files, , peer connects peer when wanting download file , accepts requests other peers download 1 of files. this, peer acting both client , server other peers, , client tracker. so, using threads , have server process in 1 thread, client process in another, , 1 connecting tracker in main thread. when peer chooses exit, want close server process ie: process in separate server thread. tried making global variable containing file descriptor can close when client exits, giving me error after exit.
here peer code:
if want know how stop other threads main thread here 1 method. create struct let's call thread_state_t
has flag tells threads stop, call active
example. in thread check in loop value , whatever need based on state.
in simple case this
#include <stdio.h> #include <pthread.h> typedef struct { int active; } thread_state_t; void* t1(void* arg) { thread_state_t* state = (thread_state_t*) arg; while(state->active > 0) { // work } return null; } int main() { pthread_t tid; thread_state_t state1; state1.active = 1; pthread_create(&tid, null, t1, (void*)&state1); // ... state1.active = 0; // ... pthread_join(tid, null); return 0; }
however example show main idea. in real implementation need make active
variable or whole thread_state_t
object thread safe (use mutex
example).
to make thread safe can use add mutex state object
typedef struct { pthread_mutex_t mutex; int active; } thread_state_t;
and add functions these
void init_state(thread_state_t* state) { state->active = 1; pthread_mutex_init(&state->mutex, null); } void remove_state(thread_state_t* state) { state->active = 0; pthread_mutex_destroy(&state->mutex); } int get_active(thread_state_t* state) { int active = 0; pthread_mutex_lock(&state->mutex); active = state->active; pthread_mutex_unlock(&state->mutex); return active; } void set_active(thread_state_t* state, int active) { pthread_mutex_lock(&state->mutex); state->active = active; pthread_mutex_unlock(&state->mutex); }
then change loop condition state->active > 0
get_active(state) > 0
, code in main thread (sleep
call here example only)
int main() { pthread_t tid; thread_state_t state; init_state(&state); pthread_create(&tid, null, t1, (void*)&state); sleep(1); set_active(&state, 0); pthread_join(tid, null); remove_state(&state); return 0; }
also way use pthread_cancel
. not best solution.
Comments
Post a Comment