Problem while compiling pthreads program - c

I tried to compile this simple pthreads program with this command
$ gcc -pthread -o pthreads pthreads.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void *myThread(void *arg);
int main()
{
pthread_t mythread;
int ret;
ret = pthread_create( &mythread, NULL, myThread, NULL );
if (ret != 0){
printf( "Can't create pthread: %s", strerror(errno));
exit(-1);
}
return 0;
}
void *myThread(void *arg){
// Thread code goes here..
printf("OK! NOW ON THE THREAD\n");
pthread_exit(NULL);
}
but when trying ./pthreads there is no output presented!!

You need to wait for the thread to finish. Otherwise you risk exiting before the thread starts executing.
...
pthread_create( &mythread, NULL, myThread, NULL );
...
// Wait for the thread to finish.
pthread_join( mythread, NULL);

You didn't wait for your thread to finish. You need to use pthread_join().

You problem comes from the fact that you're main thread is returning from main, and thus calling exit (or _exit). All running thread are killed when the program exit. In this case, the worker thread didn't have the time to execute before it is killed.
You can use pthread_join to wait for the completion of the thread before returning from main.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void *myThread(void *arg);
int main()
{
void* thread_return;
pthread_t mythread;
int ret;
ret = pthread_create(&mythread, NULL, myThread, NULL);
if (ret != 0)
{
printf("Can't create pthread: %s\n", strerror(errno));
exit(-1);
}
ret = pthread_join(mythread, &thread_return);
if (ret != 0)
{
printf("Can't join pthread: %s\n", strerror(errno));
exit(-1);
}
return 0;
}
void *myThread(void *arg)
{
printf("OK! NOW ON THE THREAD\n");
pthread_exit(NULL);
}

Sanjit's answer is certainly correct, but for the sake of enlarging your threads toolbox, you might also look at pthread_barrier_wait. When you have a simple program with a lot of threads and main looks like "start all worker threads and wait for them to finish", having main and all the workers simply wait on a barrier can be a nice way to avoid having to store all the worker thread ids and join them in a for loop. Barriers also have a lot of other neat uses that sometimes let you avoid unnecessary complexity from doing the same things with mutexes and condition variables.

Related

Why pthread_join on itself doesn't result in error or deadlock?

https://repl.it/repls/ColdSilentTriangles
#include <stdio.h>
#include <pthread.h>
pthread_t th;
void *fp(void *args) {
printf("Thread running...");
pthread_join(th, NULL);
printf("Thread waiting...");
return NULL;
}
int main(void) {
printf("Hello World\n");
pthread_create(&th, NULL, fp, NULL);
pthread_join(th, NULL);
return 0;
}
From man pthread_join,
The pthread_join() function suspends execution of the calling thread until the target thread ter-minates unless the target thread has already terminated.
Why the program doesn't result in deadlock?
Why there is no error generated?
Why "Thread waiting..." is outputed onto the screen when the pthread_join() is supposed to block the thread?
pthread_join doesn't block execution and instead returns EDEADLK in your example.

question on pthread_join() and pthread_detach()

I wrote this program to practice pthread system calls so I used some printing lines to check the results but they are escaped the output is:
Thread 1 created
Thread 2 created
test3
while I think it should be
thread 1 created
test2
thread 2 created
test3
test1
The order may change but I should have this lines so why it escape this print statements?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *function();
void *function2();
int main(int argc, char *argv[])
{
pthread_t tid;
int rc;
rc = pthread_create(&tid, NULL, function(), NULL);
if(rc > 0){
fprintf(stderr, "Error\n");
exit(1);
}
pthread_join(tid, NULL);
sleep(1);
printf("test1\n");
pthread_exit(NULL);
}
void *function(){
int rc;
pthread_t tid;
printf("Thread 1 created\n");
rc = pthread_create(&tid, NULL, function2(), NULL);
if(rc > 0){
fprintf(stderr, "Error\n");
exit(1);
}
printf("test2\n");
pthread_exit(NULL);
}
void *function2(){
pthread_detach(pthread_self());
printf("Thread 2 created\n");
printf("test3\n");
pthread_exit(NULL);
}
rc = pthread_create(&tid, NULL, function(), NULL);
You're trying to call pthread_create() with the pointer returned by calling function() as the function to run in the new thread (Remember, function arguments get evaluated before the function itself is called). Now, function() doesn't actually return any value, but it calls function2() in its body (while evaluating the arguments for another call to pthread_create()), which also doesn't return any value, but does call pthread_exit() instead. Since there's only one thread at that point because only the main process thread is running (pthread_create() hasn't actually been called yet; the call stack looks like main() -> function() -> function2()), the whole program then exits.
You need to call pthread_create() with pointers to function and function2, not the results of calling them:
rc = pthread_create(&tid, NULL, function, NULL);
etc.

Simple multithreading program with emscripten

I am trying to create a simple program with thread support using Emscripten:
#include <stdio.h>
#include <pthread.h>
void *myThreadFun(void *vargp) {
printf("From Thread \n");
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t tid;
printf("Before Thread\n");
pthread_create(&tid, NULL, myThreadFun, NULL);
printf("Before join\n");
pthread_join(tid, NULL);
printf("After Thread\n");
return 0;
}
I am executed it in Firefox and I compile using -s USE_PTHREADS=1.
This is the output I got in the console:
Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join
But I expected:
Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join
After Thread
It is like the thread is not ending. Am I missing something?
I had the same issue. I fixed it by compiling with -s PTHREAD_POOL_SIZE=x with x = number of thread created.

segmentation fault in setcontext

I'm doing some test on how a scheduler schedules a waiting thread and in the process, I want to not let OS to see a waiting thread, so I kill a thread which is waiting on a lock and start it when the lock is released, I think I should save the context of the thread before exiting and restore it when I create it again. Obviously I'm doing something wrong but I can't figure it out. (I'm very new to the subject.)
this is my code so far, it generates segmentation fault with setcontext.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ucontext.h>
ucontext_t data;
pthread_t pth;
pthread_mutex_t lock1;
void* wake_up(void* arg) {
printf("going to wake up a thread\n");
setcontext(&data);
}
void MUTEX_UNLOCK(pthread_mutex_t* lock) {
pthread_mutex_unlock(lock);
pthread_create(&pth, NULL, wake_up, NULL);
}
void MUTEX_LOCK(pthread_mutex_t* lock) {
getcontext(&data);
while(1) {
if(pthread_mutex_trylock(lock) == 0) {
printf("got the lock\n");
break;
}
else {
printf("going to exit thread\n");
pthread_exit(NULL);
}
}
}
void* routine1(void* param) {
MUTEX_LOCK(&lock1);
printf("enter any character to continue\n");
getchar();
MUTEX_UNLOCK(&lock1);
}
int main(int argc, char** argv) {
pthread_mutex_init(&lock1, 0);
pthread_t thread1[2];
int i;
for (i = 0; i < 2; i++)
pthread_create(&thread1[i], NULL, routine1, NULL);
while(1);
}
setcontext is not valid when setting the context of a thread which has exited. (The stack pointer points into a stack which has been freed.) So that's why you're getting a crash.
More in general, getcontext and setcontext are obsolete and extremely strange functions that should not be used unless you have very specific needs regarding cooperative (non-pthreads) multithreading. While you haven't described what you're trying to do, I'm 99% certain that you don't need setcontext to do it.

Pthread function starting in C

I'm actually new in processes, threads, semaphores, ipc etc(shortly operating system operations on Linux)... My problem is that I compile my code and It simply gets stuck at so funny points. Processes are executed, but they can't enter their threads' function. After that, program directly ends without doing something. I really can't figure out the problem is here or everything have problem. I don't know.
#define _GNU_SOURCE
#include <sys/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void * function1(void *ptr)
{
printf("Function 1\n"); //!Test prints
printf("Index is %d",*((int *)ptr));
sleep(1);
pthread_exit(NULL);
}
void * function2(void *ptr)
{
printf("Function 2\n"); //!Test prints
printf("Index is %d",*((int *)ptr));
sleep(2);
pthread_exit(NULL);
}
int main(){
//...
int *index;
int i;
pid_t f;
int number_of_process=5;
pthread_t thread1, thread2;
//...
for(i=0; i<number_of_process; i++)
{
f=fork();
if(f==-1)
{
printf("Fork Error!!\n");
exit(1);
}
if(f==0) //To block child processes re-enter
{
*index = i; //I store index number for each process here. I'll need them in the thread functions
break;
}
}
/*******************PARENT PROCESS********************/
if(f!=0){
// wait for all children to exit
while (f = waitpid (-1, NULL, 0)){
if (errno == ECHILD)
break;
}
exit(0);
}
/*******************CHILD PROCESS*********************/
else{
pthread_create(&thread1,NULL,function1,(void *)index);
pthread_create(&thread2,NULL,function2,(void *)index);
}
}
Processes are executed, but they can't enter their threads' function.
After that, program directly ends without doing something.
That's because the main thread (i.e. child process created by fork()) doesn't wait for the threads to complete their execution. So it gives you the impression that the program exits without calling all pthread functions.
Use pthread_join() after creating threads:
...
pthread_create(&thread1,NULL,function1,(void *)index);
pthread_create(&thread2,NULL,function2,(void *)index);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
...
The output may be interleaved due to threads printing without any synchronization.

Resources