how to pass an array value to a pthread in c

Solutions on MaxInterview for how to pass an array value to a pthread in c by the best coders in the world

showing results for - "how to pass an array value to a pthread in c"
Miley
04 Jan 2017
1void* my_Func(void *received_arr_Val){
2	
3	int single_val = (int *)received_arr_Val;
4    printf("Value: %d\n", single_val);
5	//Now use single_val as you wish
6}
7//In main:
8	int values[n];
9    pthread_create(&thread, NULL, my_Func, values[i]);
10	//i is the index number of the array value you want to send
11	//n is the total number of indexes you want (array size)
12
13//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192
Earl
12 Jan 2021
1//Runnable example
2#include <stdio.h>
3#include <stdlib.h>
4#include <pthread.h>
5
6void* my_Func(void *received_arr_Val){
7	
8	int single_val = (int *)received_arr_Val;
9    printf("Value: %d\n", single_val);
10	//Now use single_val as you wish
11}
12int main(){
13	int values[5];
14	
15	printf("\nEnter 5 numbers:\n");
16	for (int i=0; i<5; i++){
17		scanf("%d", &values[i]);
18	}
19	pthread_t tid[5];
20	for(int i=0; i<5; i++){
21		pthread_create(&(tid[i]), NULL, my_Func, values[i]);
22	}
23	for (int i=0; i<5; i++){	
24		pthread_join(tid[i], NULL);
25	}
26}
27//To run: $ gcc [C FILE].c -lpthread -lrt
28// $ ./a.out
29
30//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192