pass argunent thread c code example
Example 1: How to pass a struct value to a pthread in c?
struct my_Struct{
int val1, val2;
};
void* my_Func(void *received_struct){
struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
printf("Value 1: %d | Value 2: % \n", struct_ptr->val1, struct_ptr->val2);
}
struct my_Struct mystruct_1[n];
pthread_create(&thread, NULL, my_Func, &mystruct_1[i]);
Example 2: How to pass a struct value to a pthread in c?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct my_Struct{
int index;
int value;
};
void* my_Func(void *received_struct){
struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
printf("index: %d | value: %d \n", struct_ptr->index, struct_ptr->value);
}
int main(){
struct my_Struct mystruct_1[5];
printf("\nEnter 5 numbers:\n");
for (int i=0; i<5; i++){
scanf("%d", &mystruct_1[i].value);
mystruct_1[i].index = i;
}
pthread_t tid[5];
for(int i=0; i<5; i++){
pthread_create(&(tid[i]), NULL, my_Func, &mystruct_1[i]);
}
for (int i=0; i<5; i++){
pthread_join(tid[i], NULL);
}
}