Solution
Add lib pthread to project, otherwise error "undefined reference to `pthread_create'" occurs
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
void *thread_func(void *arg);
char msg[] = "hello world";
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_func, (void *)msg);
if(res != 0){
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finished\n");
res = pthread_join(a_thread, &thread_result);
if(res != 0){
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined, it returned %s\n", (char *)thread_result);
printf("Message is now %s\n", msg);
exit(EXIT_SUCCESS);
}
void *thread_func(void *arg)
{
printf("thread_func is running, argument was %s\n", (char *)arg);
sleep(3);
strcpy(msg, "Bye!");
pthread_exit("Thank you for the CPU time");
}
Output
Waiting for thread to finished
thread_func is running, argument was hello world
Thread joined, it returned Thank you for the CPU time
Message is now Bye!