#include <pthread.h> #include <stdio.h> #include <unistd.h>void* thread_func (void* param) {const char * p = (const char*) param; pid_t pid = 0; pthread_t tid = 0; PID = Getpid (); Tid = Pthread_self (); printf ("%s-%8u%8u\n", p, (unsigned int) PID, (unsigned int) tid);} void* thread_wait_cancel (void* p) {printf ("Thread wait Cancel, I ' M waitting for cancel\n"); Sleep (10000); printf ("If u saw me, there got be something wrong\n");} int main (int argc, char* argv[]) {pthread_t tid = 0; Pthread_create (&tid, NULL, Thread_func, (void *) "sub thread"); pthread_t tid_cancel = 0; Pthread_create (&tid_cancel, NULL, thread_wait_cancel, NULL); Wait thread tid to exit Pthread_join (Tid, NULL); Cancel a thread void* stat = 0; Pthread_cancel (Tid_cancel); Pthread_join (Tid_cancel, &stat); /* Stat =-1 stand for pthread_canceled */printf ("Cancel thread exit State:%d\n", stat); Show Main ThreaD infomation Thread_func (void *) "main thread"); return 0;}
Note that you need to add the option-lpthread when compiling. Because Pthread is not the default library for Linu, as seen in the following:
GCC Thr.c-lpthread
Linux Threads Basic use Code Demo sample