if (!pthread_equal (pthread_self (), other_thread)) pthread_join (other_thread, NULL); |
void * function(void *) |
% cc -o thread-create thread-create.c –lpthread |
#include <pthread.h> #include <stdio.h> /* Prints x’s to stderr. The parameter is unused. Does not return. */ void* print_xs (void* unused) { while (1) fputc (‘x’, stderr); return NULL; } /* The main program. */ int main () { pthread_t thread_id; /* Create a new thread. The new thread will run the print_xs function. */ pthread_create (&thread_id, NULL, &print_xs, NULL); /* Print o’s continuously to stderr. */ while (1) fputc (‘o’, stderr); return 0; } |
Listing 4.2 (thread-create2) Create Two Threads #include <pthread.h> #include <stdio.h> /* Parameters to print_function. */ struct char_print_parms { /* The character to print. */ char character; /* The number of times to print it. */ int count; }; /* Prints a number of characters to stderr, as given by PARAMETERS, which is a pointer to a struct char_print_parms. */ void* char_print (void* parameters) { /* Cast the cookie pointer to the right type. */ struct char_print_parms* p = (struct char_print_parms*) parameters; int i; for (i = 0; i < p->count; ++i) fputc (p->character, stderr); return NULL; } /* The main program. */ int main () { pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; struct char_print_parms thread2_args; /* Create a new thread to print 30,000 ’x’s. */ thread1_args.character = ’x’; thread1_args.count = 30000; pthread_create (&thread1_id, NULL, &char_print, &thread1_args); /* Create a new thread to print 20,000 o’s. */ thread2_args.character = ’o’; thread2_args.count = 20000; pthread_create (&thread2_id, NULL, &char_print, &thread2_args); return 0; } |
此程序有一个Bug,主线程创建线程的时候,穿进去的参数是局部变量,如果主线程在从线程之前退出,则局部变量会被释放,然而从线程却可能仍然要访问这些变量,就会出错。因而应该应用join使得主线程等待从线程结束。
Revised Main Function for thread-create2.c int main () { pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; struct char_print_parms thread2_args; /* Create a new thread to print 30,000 x’s. */ thread1_args.character = ’x’; thread1_args.count = 30000; pthread_create (&thread1_id, NULL, &char_print, &thread1_args); /* Create a new thread to print 20,000 o’s. */ thread2_args.character = ’o’; thread2_args.count = 20000; pthread_create (&thread2_id, NULL, &char_print, &thread2_args); /* Make sure the first thread has finished. */ pthread_join (thread1_id, NULL); /* Make sure the second thread has finished. */ pthread_join (thread2_id, NULL); /* Now we can safely return. */ return 0; } |
用线程计算素数 #include <pthread.h> #include <stdio.h> /* Compute successive prime numbers (very inefficiently). Return the Nth prime number, where N is the value pointed to by *ARG. */ void* compute_prime (void* arg) { int candidate = 2; int n = *((int*) arg); while (1) { int factor; int is_prime = 1; /* Test primality by successive division. */ for (factor = 2; factor < candidate; ++factor) if (candidate % factor == 0) { is_prime = 0; break; } /* Is this the prime number we’re looking for? */ if (is_prime) { if (--n == 0) /* Return the desired prime number as the thread return value. */ return (void*) candidate; } ++candidate; } return NULL; } int main () { pthread_t thread; int which_prime = 5000; int prime; /* Start the computing thread, up to the 5,000th prime number. */ pthread_create (&thread, NULL, &compute_prime, &which_prime); /* Do some other work here... */ /* Wait for the prime number thread to complete, and get the result. */ pthread_join (thread, (void*) &prime); /* Print the largest prime it computed. */ printf(“The %dth prime number is %d.\n”, which_prime, prime); return 0; } |
#include <pthread.h> void* thread_function (void* thread_arg) { /* Do work here... */ } int main () { pthread_attr_t attr; pthread_t thread; pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); pthread_create (&thread, &attr, &thread_function, NULL); pthread_attr_destroy (&attr); /* Do work here... */ /* No need to join the second thread. */ return 0; } |
#include <malloc.h> #include <pthread.h> #include <stdio.h> /* The key used to associate a log file pointer with each thread. */ static pthread_key_t thread_log_key; /* Write MESSAGE to the log file for the current thread. */ void write_to_thread_log (const char* message) { FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key); fprintf (thread_log, “%s\n”, message); } /* Close the log file pointer THREAD_LOG. */ void close_thread_log (void* thread_log) { fclose ((FILE*) thread_log); } void* thread_function (void* args) { char thread_log_filename[20]; FILE* thread_log; /* Generate the filename for this thread’s log file. */ sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ()); /* Open the log file. */ thread_log = fopen (thread_log_filename, “w”); /* Store the file pointer in thread-specific data under thread_log_key. */ pthread_setspecific (thread_log_key, thread_log); write_to_thread_log (“Thread starting.”); /* Do work here... */ return NULL; } int main () { int i; pthread_t threads[5]; /* Create a key to associate thread log file pointers in thread-specific data. Use close_thread_log to clean up the file pointers. */ pthread_key_create (&thread_log_key, close_thread_log); /* Create threads to do the work. */ for (i = 0; i < 5; ++i) pthread_create (&(threads[i]), NULL, thread_function, NULL); /* Wait for all threads to finish. */ for (i = 0; i < 5; ++i) pthread_join (threads[i], NULL); return 0; } |
Linux可以提供回收器(cleanup handler),它是一个函数,在线程退出的时候被调用。
调用pthread_cleanup_push可以注册一个回收器。
调用pthread_cleanup_pop可以注销一个回收器。
pthread_cleanup_pop(0)仅仅注销一个回收器。
pthread_cleanup_pop(1)不仅仅注销这个回收器,而且调用它。
#include <malloc.h> #include <pthread.h> /* Allocate a temporary buffer. */ void* allocate_buffer (size_t size) { return malloc (size); } /* Deallocate a temporary buffer. */ void deallocate_buffer (void* buffer) { free (buffer); } void do_some_work () { /* Allocate a temporary buffer. */ void* temp_buffer = allocate_buffer (1024); /* Register a cleanup handler for this buffer, to deallocate it in case the thread exits or is cancelled. */ pthread_cleanup_push (deallocate_buffer, temp_buffer); /* Do some work here that might call pthread_exit or might be cancelled... */ /* Unregister the cleanup handler. Because we pass a nonzero value, this actually performs the cleanup by calling deallocate_buffer. */ pthread_cleanup_pop (1); } |
pthread_mutex_t mutex; pthread_mutex_init (&mutex, NULL); |
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <pthread.h> struct job { struct job* next; int value; }; struct job* job_queue; void process_job(struct job*); pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void * process_queue_function (void * arg) { while(1) { struct job* next_job; pthread_mutex_lock(&job_queue_mutex); if(job_queue == NULL) next_job = NULL; else { printf("begin removing a job...\n"); next_job = job_queue; job_queue = job_queue->next; printf("after removing a job...\n"); } pthread_mutex_unlock(&job_queue_mutex); if(next_job == NULL) { sleep(5); continue; } process_job(next_job); free(next_job); } return NULL; } void process_job(struct job* p) { printf("The value is : %d.\n", p->value); } void enqueue_job(struct job* new_job) { pthread_mutex_lock(&job_queue_mutex); printf("begin inserting a job...\n"); new_job->next = job_queue; job_queue = new_job; printf("after inserting a job...\n"); pthread_mutex_unlock(&job_queue_mutex); } void * insert_queue_function(void * arg) { int i = 0; while(i < 20) { sleep(1); printf("put the value: %d.\n", i); struct job* new_job = (struct job*)malloc(sizeof(struct job)); new_job->next = NULL; new_job->value = i; enqueue_job(new_job); i++; } } int main() { pthread_t insert_thread, process_thread; pthread_create(&insert_thread, NULL, &insert_queue_function, NULL); pthread_create(&process_thread, NULL, &process_queue_function, NULL); pthread_join(insert_thread, NULL); pthread_join(process_thread, NULL); } |