write simple code to create pthread and execute the code

/* Simple Pthreads example. */
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void* ThreadFunc(void* arg);
int main(int argc, char argv[])
{
pthread_t idThread;
puts("Let’s create a thread!");
pthread_create(&idThread, NULL, ThreadFunc, (void*) 5);
pthread_join(idThread, NULL);
}
void* ThreadFunc(void* arg)

{
int i, n;
/* Get the value of the argument passed in. */
n = (int) arg;
/* Do stuff! */
for (i = 0; i < n; i++)
printf("Loop %d: La la la!\n", i + 1);
return NULL;
}

execute on teraminal

gcc foo.c -o foo -Wall -lpthread

./foo

 

result

Let’s create a thread!
Loop 1: La la la!
Loop 2: La la la!
Loop 3: La la la!
Loop 4: La la la!
Loop 5: La la la!

Comments

Popular posts from this blog

Write a code to pass a simple integer to each thread and measure time taken by each thread with out and with pthread_join. The calling thread uses a unique data structure for each thread, insuring that each thread's argument remains intact throughout the program.

print hello world using pthread through creating 5 threads.