how to pass a struct value to a pthread in c 3f

Solutions on MaxInterview for how to pass a struct value to a pthread in c 3f by the best coders in the world

showing results for - "how to pass a struct value to a pthread in c 3f"
Mauricio
14 May 2018
1struct my_Struct{
2	int val1, val2;
3};
4void* my_Func(void *received_struct){
5  	//Creating a pointer to point to the received struct
6	struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
7    printf("Value 1: %d | Value 2: % \n", struct_ptr->val1, struct_ptr->val2);
8	//Now use 'struct_ptr->val1', 'struct_ptr->val2' as you wish
9}
10//In main:
11		struct my_Struct mystruct_1[n];
12		pthread_create(&thread, NULL, my_Func, &mystruct_1[i]);
13		//i is the index number of mystruct_1 you want to send
14		//n is the total number of indexes you want
15
16//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192
Federica
31 Jul 2016
1//Runnable example
2#include <stdio.h>
3#include <stdlib.h>
4#include <pthread.h>
5
6struct my_Struct{
7	int index;
8	int value;
9};
10void* my_Func(void *received_struct){
11	struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
12    printf("index: %d  |  value: %d \n", struct_ptr->index, struct_ptr->value);
13	//Now use 'struct_ptr->index', 'struct_ptr->value' as you wish
14}
15int main(){
16	struct my_Struct mystruct_1[5];
17	
18	printf("\nEnter 5 numbers:\n");
19	for (int i=0; i<5; i++){
20		scanf("%d", &mystruct_1[i].value);
21		mystruct_1[i].index = i;
22	}
23	pthread_t tid[5];
24	for(int i=0; i<5; i++){
25		pthread_create(&(tid[i]), NULL, my_Func, &mystruct_1[i]);
26	}
27	for (int i=0; i<5; i++){	
28		pthread_join(tid[i], NULL);
29	}
30}
31//To run: gcc [C FILE].c -lpthread -lrt
32// ./a.out
33
34//Grepper Profile: https://www.codegrepper.com/app/profile.php?id=9192