how to pass an array to a thread in c?
void* my_Func(void *received_arr_Val){
int single_val = (int *)received_arr_Val;
printf("Value: %d\n", single_val);
//Now use single_val as you wish
}
//In main:
int values[n];
pthread_create(&thread, NULL, my_Func, values[i]);
//i is the index number of the array value you want to send
//n is the total number of indexes you want (array size)
//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192
4
2
//Runnable Example
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* my_Func(void *received_arr){
int *arr = (int *)received_arr;
for (int i=0; i<5; i++){
printf("Value %d: %d\n", i+1, arr[i]);
}
//Now use arr[] as you wish
}
int main(){
int values[5];
printf("\nEnter 5 numbers:\n");
for (int i=0; i<5; i++){
scanf("%d", &values[i]);
}
pthread_t tid;
pthread_create(&tid, NULL, my_Func, (void *)values);
pthread_join(tid, NULL);
}
//To run: gcc [C FILE].c -lpthread -lrt
//./a.out
//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192
Thank you!
2
0
0
0
//Runnable example
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* my_Func(void *received_arr_Val){
int single_val = (int *)received_arr_Val;
printf("Value: %d\n", single_val);
//Now use single_val as you wish
}
int main(){
int values[5];
printf("\nEnter 5 numbers:\n");
for (int i=0; i<5; i++){
scanf("%d", &values[i]);
}
pthread_t tid[5];
for(int i=0; i<5; i++){
pthread_create(&(tid[i]), NULL, my_Func, values[i]);
}
for (int i=0; i<5; i++){
pthread_join(tid[i], NULL);
}
}
//To run: $ gcc [C FILE].c -lpthread -lrt
// $ ./a.out
//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192
Thank you!
0
0
4.4
5
void* my_Func(void *received_arr){
int *arr = (int *)received_arr;
for (int i=0; i<5; i++){
printf("Value %d: %d\n", i+1, arr[i]);
}
//Now use arr[] as you wish
}
//In main:
int values[n];
pthread_create(&thread, NULL, my_Func, (void *)values);
//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192
Thank you!
5
0
Are there any code examples left?
New code examples in category C
-
C 2022-03-27 22:30:45 Problem Statement Print the following output: \ Input Format IN Output Format \
-
C 2022-03-27 18:30:08 how to free memory in c
-
C 2022-03-27 18:00:14 linux command line windows
-
C 2022-03-27 18:00:02 C example of if else
-
C 2022-03-27 17:10:18 sum of digits in c using for loop
-
C 2022-03-27 12:35:50 replace word in c
-
C 2022-03-27 07:40:11 How to setup a line length marker in vim
-
C 2022-03-27 07:35:09 Multi Select with icons htm;