Created
August 31, 2011 17:13
-
-
Save gennad/1184087 to your computer and use it in GitHub Desktop.
Multithreading in Unix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Compile with g++ -o multithreading.o multithreading.cc -lpthread | |
| #include <pthread.h> | |
| #include <errno.h> | |
| #include <signal.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <time.h> | |
| #include <unistd.h> | |
| #include <string.h> | |
| typedef struct my_struct { | |
| int data; | |
| int random_number; | |
| } my_struct_t; | |
| 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); | |
| } | |
| } | |
| int main(int argc, char **argv){ | |
| sigset_t oSignalSet; | |
| 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); | |
| int iReturnValue3 = pthread_create(&iThreadId, NULL, &thread, (void *)&st3); | |
| 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); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment