views:

170

answers:

2
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
void *thread_function(void *arg);
sem_t bin_sem;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int main() {
    int res;
    pthread_t a_thread;
    void *thread_result;
    res = sem_init(&bin_sem, 0, 0);
    if (res != 0) {
        perror(“Semaphore initialization failed”);
        exit(EXIT_FAILURE);
    }
    res = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (res != 0) {
        perror(“Thread creation failed”);
        exit(EXIT_FAILURE);
    }
    printf(“Input some text. Enter ‘end’ to finish\n”);
    while(strncmp(“end”, work_area, 3) != 0) {
        fgets(work_area, WORK_SIZE, stdin);
        sem_post(&bin_sem);
    }
    printf(“\nWaiting for thread to finish...\n”);
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) {
        perror(“Thread join failed”);
        exit(EXIT_FAILURE);
    }
    printf(“Thread joined\n”);
    sem_destroy(&bin_sem);
    exit(EXIT_SUCCESS);
}
void *thread_function(void *arg) {
    sem_wait(&bin_sem);
    while(strncmp(“end”, work_area, 3) != 0) {
         printf(“You input %d characters\n”, strlen(work_area) -1);
         sem_wait(&bin_sem);}
    pthread_exit(NULL);
}

In the program above, when the semaphoe is released using sem_post(), is it possible that the fgets and the counting fuction in thread_function execute simultaneously .And I think this program fails in allowing the second thread to count the characters before the main thread reads the keyboard again. Is that right?

+1  A: 

The second thread will only read characters after sem_wait has returned, signaling that a sem_post has been called somewhere, so I think that is fine.

As for fgets and the counting function, those two could be running simultaneously.

I would recommend a mutex lock on the work_area variable in this case, because if the user is editing the variable in one thread while it is being read in another thread, problems will occur.

You can either use a mutex or you can use a semaphore and set the initial count on it to 1.

If you implement a mutex or use a semaphore like that though, make sure to put the mutex_lock after sema_wait, or else a deadlock may occur.

samoz
A: 

In this example you want to have a mutex around the read & writes of the shared memory.

I know this is an example, but the following code:

fgets(work_area, WORK_SIZE, stdin);

Should really be:

fgets(work_area, sizeof(work_area), stdin);

If you change the size of work_area in the future (to some other constant, etc), it's quite likely that changing this second WORK_SIZE could be missed.

jthompson