Multithreaded semaphore program

Thomas

I've spent quite a few hours on trying to figure this one out and I'm completly stuck. The program is supposed to start 6 threads. Where some threads start where others end. Right now, I'm trying to get one single thread (thread 0) to execute. The caps lock commenting shows where I have added code and done my mistakes. My main struggle here is dealing with the pointers. Could anyone give me any pointers (ha..ha.. :c )?

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define SHARED 1
sem_t sem[6];           

struct threadargs
 {
 int id;        /* thread number */
 int sec;       /* how many sec to sleep */
 int signal[6]; /* which threads to signal when done */
 };                 

void *tfunc(void *arg)
 {
 int i;
 struct threadargs *targs=arg;
 sem_wait(sem);                              //WAIT FOR OWN SEMAPHORE
 printf("Thread %d is running\n", targs->id);
 sleep(targs->sec);
 printf("Thread %d is completed and may wake others..\n", targs->id);
 for(i=0; i<6; i++)                          //ITERATE OVER signal_ARRAY & 
  {                                          //WAKE THREAD NUMBER i IF 
  if(targs->signal[i] == 1)                  //signal[i] IS 1
    pthread_cond_signal(&sem[i]);
  }
 }

int main(void)
 {
 int i, j;
 struct threadargs *targs[6];   
 pthread_t tid[6];
 for(i=0; i<6; i++)
 {
 targs[i] = (struct threadargs*) malloc(sizeof(struct threadargs));
 for(j=0; j<6; j++)
  { targs[i]->signal[j]=0; }   
 }
targs[0]->id=1;         
targs[0]->sec=1;        
targs[0]->signal[1]=1;      
targs[0]->signal[4]=1;
sem[0] = 0;                                 //INITIALIZE THREAD'S SEMAPHORE TO 0 or 1
pthread_create(targs[0], NULL, tfunc, NULL) // START THREAD

for(i=0; i<6; i++)
 pthread_join(tid[i], NULL);
return 0; 
 }
Michel Megens

Alright. First things first, I do recommend taking a second look at your coding style. It is of course highly subjective and I won't say yours is bad, but it took me a while to figure it out (if you really want to know, I recommend the Linux coding style for C/C++ code).

Lets get on with your problem. As far as I can see, the main issue seems that you're basically comparing pointers to apples with pointers to banana's (in other words, you're using the wrong pointer type in the wrong place).

To make sure that calls to functions and the like are correct, make sure to look up the API documentation for functions that are new to you (examples: pthread_create, sem_init, sem_wait, sem_post, pthread_cond_signal).

As you can see, pthread_cond_signal doesn't take a sem_t* as argument, and therefore you can't pass one to it and expect it to work. Below you'll find an example program showing how semaphores are used.

First, a new thread is created which will be put in waiting state instantly. As soon as the main tread finished counting from 0 to 150, it will post ('unlock') the semaphore and allowing the second thread to finish its execution.

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

static sem_t sem_thread_one;
static pthread_t thread_one_data;

static int x;

static void *tfunc(void *arg)
{
    sem_wait(&sem_thread_one);
    printf("Thread 1 is running. The value of x is %i\n", x);
    return NULL;
}

int main(int argc, char **argv)
{
    sem_init(&sem_thread_one, 0 /* don't share between processes */, 0);

    if(pthread_create(&thread_one_data, NULL, &tfunc, NULL)) {
        fprintf(stderr, "Could not create thread, exiting!\n");
        return -EXIT_FAILURE;
    }

    while(x < 150) {
        x++;
    }

    sem_post(&sem_thread_one);

    if(pthread_join(thread_one_data, NULL)) {
        fprintf(stderr, "Could not join threads, exiting!\n");
        return -EXIT_FAILURE;
    }

    sem_destroy(&sem_thread_one);
    printf("Program ran succesfully!\n");
    return -EXIT_SUCCESS;
}

Save in a file sem.c and compile & link using:

gcc -Wall -Os -pthread -o sem_test sem.c

Now a second example, but now using pthread_cond_t. The functionality of the program is somewhat similar, it waits for a counter to reach a certain number.

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

static pthread_t thread_one_data, thread_two_data;
static volatile int x, y, idx = 10;
static int count = 1;

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

static void *cond_test_wait(void *arg)
{
    pthread_mutex_lock(&mutex);
    while(count < 10) {
        printf("Waiting for `count < 10' to become true\n");
        pthread_cond_wait(&condition, &mutex);
    }
    pthread_mutex_unlock(&mutex);

    printf("Test wait thread finished. Value of count: %i\n", count);
    return NULL;
}

static void *cond_test_signal(void *arg)
{
    while(count < 10) {
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&condition);

        /* do more intelligent things here */
        count++;
        pthread_mutex_unlock(&mutex);
    }

    printf("Test signal thread finished\n");
    return NULL;
}

int main(int argc, char **argv)
{

    if(pthread_create(&thread_one_data, NULL, &cond_test_wait, NULL)) {
        fprintf(stderr, "Could not create thread, exiting!\n");
        return -EXIT_FAILURE;
    }

    if(pthread_create(&thread_two_data, NULL, &cond_test_signal, NULL)) {
        fprintf(stderr, "Could not create thread, exiting!\n");
        return -EXIT_FAILURE;
    }

    pthread_join(thread_one_data, NULL);
    pthread_join(thread_two_data, NULL);

    pthread_cond_destroy(&condition);
    pthread_mutex_destroy(&mutex);

    printf("Program ran succesfully!\n");
    return -EXIT_SUCCESS;
}

Save in a file cond.c and compile & link using:

gcc -o cond -pthread -Os -Wall cond.c

Do note how neat condition work in this example. You can use them to wait until any expression (= condition) becomes true. After the condition becomes true normal execution continue's.

If you need any more help, don't hesitate to ask in the comments. Good luck combining the above examples to fix up your program.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Multithreaded program logic

From Dev

Simple multithreaded program segfault

From Dev

Unexpected output in a multithreaded program

From Dev

Multithreaded program that simulates a shell

From Dev

Unexpected result in multithreaded program

From Dev

Swing graphics in multithreaded program

From Dev

Simple multithreaded program segfault

From Dev

multithreaded mutisocket program

From Dev

Why is the multithreaded version of this program slower?

From Dev

Multithreaded C Program Not Functioning With Args

From Dev

Is this a decent structure for a multithreaded videocoacher program?

From Dev

Can a multithreaded functional program be deterministic?

From Dev

Is there an Advantage to Shared Memory in a Multithreaded Program?

From Dev

Semaphore simulation program: Segmentation Fault error

From Dev

Will signals be delivered to a program blocked on POSIX semaphore?

From Dev

When does the OS switch threads in a multithreaded program?

From Dev

How to delete objects in multithreaded c++ program

From Dev

Would a connection Pool benefit a multithreaded Java program

From Dev

How to optimize multithreaded program for use in LSF?

From Dev

Multithreaded ruby program only uses 100% cpu

From Dev

why there is a deadlock in multithreaded program given below

From Dev

Catching signals such as SIGSEGV and SIGFPE in multithreaded program

From Dev

Multithreaded program works only with print statements

From Dev

Why is my multithreaded program executing sequentially?

From Dev

How to write below multithreaded program best way

From Dev

Getting System.ArgumentOutOfRangeException in Multithreaded UI program

From Dev

Reason behind segmentation fault in multithreaded program

From Dev

How to optimize multithreaded program for use in LSF?

From Dev

Multithreaded program runs while loop extra times

Related Related

  1. 1

    Multithreaded program logic

  2. 2

    Simple multithreaded program segfault

  3. 3

    Unexpected output in a multithreaded program

  4. 4

    Multithreaded program that simulates a shell

  5. 5

    Unexpected result in multithreaded program

  6. 6

    Swing graphics in multithreaded program

  7. 7

    Simple multithreaded program segfault

  8. 8

    multithreaded mutisocket program

  9. 9

    Why is the multithreaded version of this program slower?

  10. 10

    Multithreaded C Program Not Functioning With Args

  11. 11

    Is this a decent structure for a multithreaded videocoacher program?

  12. 12

    Can a multithreaded functional program be deterministic?

  13. 13

    Is there an Advantage to Shared Memory in a Multithreaded Program?

  14. 14

    Semaphore simulation program: Segmentation Fault error

  15. 15

    Will signals be delivered to a program blocked on POSIX semaphore?

  16. 16

    When does the OS switch threads in a multithreaded program?

  17. 17

    How to delete objects in multithreaded c++ program

  18. 18

    Would a connection Pool benefit a multithreaded Java program

  19. 19

    How to optimize multithreaded program for use in LSF?

  20. 20

    Multithreaded ruby program only uses 100% cpu

  21. 21

    why there is a deadlock in multithreaded program given below

  22. 22

    Catching signals such as SIGSEGV and SIGFPE in multithreaded program

  23. 23

    Multithreaded program works only with print statements

  24. 24

    Why is my multithreaded program executing sequentially?

  25. 25

    How to write below multithreaded program best way

  26. 26

    Getting System.ArgumentOutOfRangeException in Multithreaded UI program

  27. 27

    Reason behind segmentation fault in multithreaded program

  28. 28

    How to optimize multithreaded program for use in LSF?

  29. 29

    Multithreaded program runs while loop extra times

HotTag

Archive