In: Computer Science
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 3
/* create thread argument struct for thr_func() */
typedef struct _thread_data_t {
int tid;
double stuff;
} thread_data_t;
/* thread function */
void *thr_func(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
printf("hello from thr_func, thread id: %d\n", data->tid);
pthread_exit(NULL);
}
int main(int argc, char **argv) {
pthread_t thr[NUM_THREADS];
int i, rc;
thread_data_t thr_data[NUM_THREADS];
/* create threads */
for (i = 0; i < NUM_THREADS; ++i) {
thr_data[i].tid = i;
pthread_create(&thr[i], NULL, thr_func, &thr_data[i])
}
/* block until all threads complete */
for (i = 0; i < NUM_THREADS; ++i) {
pthread_join(thr[i], NULL);
}
return EXIT_SUCCESS;
}
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
Many aspects of C-language threading (and indeed threading in other languages) are non-deterministic. That is, they cannot be predicted, and vary from one run depending on factors that you have no control over.
C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature.
The above program Gives output for the first Compile & Run ->
hello from thre_func, thread id : 0
hello from thre_func, thread id: 1
hello from thre_func, thread id: 2
-------------------------------------------------------------------
, for second-time compile and run->
hello from thre_func, thread id: 2
hello from thre_func, thread id: 1
hello from thre_func, thread id: 0
-------------------------------------------------------------------
and for the third time Runs gives->
hello from thre_func, thread id : 1
hello from thre_func, thread id: 2
hello from thre_func, thread id: 0
-> thread_data_t thr_data[NUM_THREADS]; is called a function that passes the argument "NUM_THREADS" defines in Macro and assign 3 to it.
pthread_create(&thr[i], NULL, thr_func, &thr_data[i]);
here above function creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code but in the above program, it is called 3 times with the help of for loop