pthread

研究了一陣pthread, 其實都唔係太難用,注意在Thread的model內所有Thread係Share同一組的Memory Data,This is the responsibility the programmer to ensure the data integrity and avoid race condition:

有以下要點:

Initialization:

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
Child Thread Definition:
void * child_process(void* arg) { … }

To Start a thread:
pthread_create(pthread_t* _thread, pthread_attr_t* _attr, (void*) _function, (void *) _data);

_thread = Thread ID returned
_attr = The Thread Attribute
_function = The Function Pointer
_data = the pointer of the data passed to the child process

return 0 on success

To collect a finalized thread(remember never stop a thread externally, the thread should end by itself):
pthread_join(pthread_t _thread, NULL)

This is to Wait the _thread to finish and collect the remains of the thread.

Play Source:

#include /* for printf */
#include /* for rand() */
#include

/* for INT_MAX */
#include
#include /* for gettimeofday */
#include /* for all the pthread functions */typedef struct thread_data_s {
int level;
int value;
} thread_data_t;

pthread_attr_t attr;

void print_level(thread_data_t* t_data){
int i;
for(i=0; i< t_data->level; i++){
printf(”\t”);
}
printf(”%d\n”,t_data->value);
}
void* child_process(void *args){
// Data Allocation
pthread_t t1 = (pthread_t)NULL, t2= (pthread_t)NULL; /* thread id’s of children */
thread_data_t *t1_data, *t2_data, *t_data;
t1_data = (thread_data_t*)malloc(sizeof(thread_data_t));
t2_data = (thread_data_t*)malloc(sizeof(thread_data_t));
t_data = (thread_data_t*)args;
//printf(”I am the child of level=%d, value=%d\n”, t_data->level, t_data->value);
print_level(t_data);
if(t_data->level == 0) return;
t1_data->level=t_data->level-1;
t1_data->value=t_data->value*2;
if (pthread_create(&t1, &attr, child_process, (void *)t1_data) != 0) {
/* thread create failed. Give up. */
perror(”Unable to create thread for 1st”);
free(t1_data); pthread_exit((void *)-1);
}

t2_data->level=t_data->level-1;
t2_data->value=t_data->value*2+1;
if (pthread_create(&t2, &attr, child_process, (void *)t2_data) != 0) {
/* thread create failed. Give up. */
perror(”Unable to create thread for 2nd”);
}
if (t1 != 0) { pthread_join(t1, NULL); free(t1_data); }
if (t2 != 0) { pthread_join(t2, NULL); free(t2_data); }

}

int
main(int argc, char* argv[]){
pthread_t me = pthread_self();
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
printf(”I am the parent\n”);
thread_data_t initial_data;
pthread_t initial_child;
initial_data.level=5;
initial_data.value=1;
if (pthread_create(&initial_child, &attr, child_process, (void *)&initial_data) != 0) {
/* thread create failed. Give up. */
perror(”Unable to create first thread”);
}
if( initial_child != 0) {
pthread_join(initial_child, NULL);
}
}

Leave a Reply