Created
October 7, 2013 15:20
-
-
Save siddontang/6869724 to your computer and use it in GitHub Desktop.
Threads Creation and Execution Example
This file contains 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> | |
void initArray(int* array, int N) | |
{ | |
int i = 0; | |
for(i = 0; i < N; i++) | |
{ | |
array[i] = (int)random(); | |
} | |
} | |
struct ThreadArgs | |
{ | |
int* A; | |
int* B; | |
int* C; | |
int index; | |
}; | |
void* threadFunc(void* arg) | |
{ | |
struct ThreadArgs* args = (struct ThreadArgs*)arg; | |
int index = args->index; | |
args->C[index] = args->A[index] + args->B[index]; | |
return NULL; | |
} | |
void printArray(int* array, int N) | |
{ | |
int i = 0; | |
for(i = 0; i < N; i++) | |
{ | |
printf("%010d ", array[i]); | |
} | |
printf("\n"); | |
} | |
int main() | |
{ | |
int N; | |
int* A = NULL; | |
int* B = NULL; | |
int* C = NULL; | |
int i = 0; | |
struct ThreadArgs* args = NULL; | |
pthread_t* threads; | |
printf("Input array size N: "); | |
scanf("%d", &N); | |
A = (int*)malloc(N * sizeof(int)); | |
B = (int*)malloc(N * sizeof(int)); | |
C = (int*)malloc(N * sizeof(int)); | |
args = (struct ThreadArgs*)malloc(N * sizeof(struct ThreadArgs)); | |
threads = (pthread_t*)malloc(N * sizeof(pthread_t)); | |
initArray(A, N); | |
initArray(B, N); | |
for(i = 0; i < N; i++) | |
{ | |
args[i].A = A; | |
args[i].B = B; | |
args[i].C = C; | |
args[i].index = i; | |
pthread_create(&threads[i], NULL, threadFunc, &args[i]); | |
} | |
for(i = 0; i < N; i++) | |
{ | |
pthread_join(threads[i], NULL); | |
} | |
printArray(A, N); | |
printArray(B, N); | |
printArray(C, N); | |
free(A); | |
free(B); | |
free(C); | |
free(args); | |
free(threads); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment