from:http://programming-in-linux.blogspot.com/2008/03/multithreading-example-in-cc-using.html
在网上找到了一个linux多线程的demo,原博客已经删除了,我做了些注释编辑一下,希望对读者有用。
demo展示了如何创建线程,如何初始化,如何传递参数等。
thread_example.cc
#include <pthread.h> #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <string.h> //define a struct to pass parameters typedef struct my_struct { int data; int random_number; }my_struct_t; /*=== define the thread method ======*/ void * thread(void * str) { my_struct_t *local_str = (my_struct_t *)str; int i; for (i=0;i<5;i++) { sleep(local_str->random_number); printf("Hello! I am thread %d, i was sleeping for %d seconds\n", local_str->data, local_str->random_number); } } /*===========================================================================*/ /*=== main method ====*/ int main(int argc, char **argv){ sigset_t oSignalSet; //initialise and empty a signal set sigemptyset(&oSignalSet); sigaddset(&oSignalSet, SIGINT); sigaddset(&oSignalSet, SIGABRT); sigaddset(&oSignalSet, SIGQUIT); pthread_sigmask(SIG_BLOCK, &oSignalSet, NULL); pthread_t iThreadId; // // Declare variable to hold seconds on clock. // time_t seconds; // // Get value from system clock and // place in seconds variable. // time(&seconds); // // Convert seconds to a unsigned // integer. // srand((unsigned int) seconds); my_struct_t st1; my_struct_t st2; my_struct_t st3; st1.data = 1; st2.data = 2; st3.data = 3; st1.random_number = rand()%10; st2.random_number = rand()%10; st3.random_number = rand()%10; printf("Parent: Creating and calling threads...\n"); int iReturnValue1 = pthread_create(&iThreadId, NULL, &thread, (void *)&st1); int iReturnValue2 = pthread_create(&iThreadId, NULL, &thread, (void *)&st2); // pthread_cancel(iThreadId); int iReturnValue3 = pthread_create(&iThreadId, NULL, &thread, (void *)&st3); //cancel pThread pthread_cancel(iThreadId); if (iReturnValue1 < 0 || iReturnValue2 < 0 || iReturnValue2 < 0) { printf("error creating thread '%s'.\n", strerror(errno)); } int iSignalNumber; sigwait(&oSignalSet, &iSignalNumber); printf("exit after receiving signal #%d.\n", iSignalNumber); exit(0); }
ericyang$ g++ -o thread_example.o thread_example.cc ericyang$thread_example.o
输出结果:
Parent: Creating and calling threads... Hello! I am thread 2, i was sleeping for 1 seconds Hello! I am thread 2, i was sleeping for 1 seconds Hello! I am thread 2, i was sleeping for 1 seconds Hello! I am thread 1, i was sleeping for 4 seconds Hello! I am thread 2, i was sleeping for 1 seconds Hello! I am thread 2, i was sleeping for 1 seconds Hello! I am thread 1, i was sleeping for 4 seconds Hello! I am thread 1, i was sleeping for 4 seconds Hello! I am thread 1, i was sleeping for 4 seconds Hello! I am thread 1, i was sleeping for 4 seconds