Created
May 12, 2017 14:00
-
-
Save spokzers/097d004719778f3ebe4930d2342d3cd3 to your computer and use it in GitHub Desktop.
Returning int and string from a thread
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
void *returnintanswer( void *ptr ); | |
void *returnstringanswer( void *ptr ); | |
int main() | |
{ | |
// char buffer[1024]; | |
// int rcount = read(0, buffer, sizeof(buffer)); | |
int a[] = {2, 4}; | |
pthread_t thread1, thread2; | |
const char *message1 = "Thread 1"; | |
const char *message2 = "Thread 2"; | |
int iret1, iret2; | |
/* Create independent threads each of which will execute function */ | |
iret1 = pthread_create( &thread1, NULL, returnintanswer, (void*) a); | |
if(iret1) | |
{ | |
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1); | |
exit(EXIT_FAILURE); | |
} | |
iret2 = pthread_create( &thread2, NULL, returnstringanswer, (void*) a); | |
if(iret2) | |
{ | |
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2); | |
exit(EXIT_FAILURE); | |
} | |
printf("pthread_create() for thread 1 returns: %d\n",iret1); | |
printf("pthread_create() for thread 2 returns: %d\n",iret2); | |
/* Wait till threads are complete before main continues. Unless we */ | |
/* wait we run the risk of executing an exit which will terminate */ | |
/* the process and all threads before the threads have completed. */ | |
int answer = 0; | |
pthread_join( thread1, (void **)&answer); | |
// char an[4] doesnt work | |
char *an = (char *) malloc(4); | |
pthread_join( thread2, (void **)&an); | |
printf("ans int: %d\n", answer); | |
printf("ans string: %s\n", an); | |
exit(EXIT_SUCCESS); | |
} | |
void *returnintanswer( void *ptr ) | |
{ | |
int answer = 0; | |
int *val = (int *)ptr; | |
answer = val[0] + val[1]; | |
pthread_exit((void **)answer); | |
} | |
void *returnstringanswer( void *ptr ) | |
{ | |
char *answer; | |
/* Initial memory allocation */ | |
answer = (char *) malloc(4); | |
// char answer[4] ===> array type declarations dont work | |
int *val = (int *)ptr; | |
int ans = 0; | |
ans = val[0] + val[1]; | |
int pcount = sprintf(answer, "%d\n", ans); | |
// printf("%d", pcount); | |
pthread_exit((void **)answer); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment