Siva Kannan
Siva Kannan

Reputation: 2471

how to suspend the other threads when one thread is wishing to execute or print something?

i am new to multithreading in C(LINUX)

i am doing a multiple client server(single) program ,here i am using threads for execution of the server,so i need when a client is waiting for reply other threads(other server threads) should not run,

        while(n = read(conn->sock, buffer, sizeof(buffer))  > 0 )
        {
            //HERE I NEED THE LOCK THE OTHER THREADS FROM THEIR EXECUTION

                    //process
                    //process
                    //end of process

            //HERE I NEED TO RELEASE LOCK FOR THE OTHER THREADS EXECUTION



        }
    }

i did not find anything specific on the net,even some example URL will be helpful

Upvotes: 1

Views: 233

Answers (5)

alk
alk

Reputation: 70931

To protect the concurrent access to a shared resource a simple (fast) mutex would do.

#include <pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

[...]


void some_func(void)
{
  [...]

  pthread_mutex_lock(&mutex);

  /* Access to shared resource here (print to stdout for example). */

  pthread_mutex_unlock(&mutex);

  [...]
}

Please note that this code lacks error checking for the sake of readability.

Upvotes: 0

Nowayz
Nowayz

Reputation: 1948

You should use Mutual Exclusion (mutex). If you're on Windows I would use EnterCriticalSection on a critical section object.

You can also use std::mutex, which has been added in C++11 to try and create a standardized technique for this sort of thing.

Basically you have the thread that needs to transmit or access something take 'ownership' of the mutex and all other threads would check before taking action to see if the mutex is already owned. If the mutex is owned the other threads would wait until it is released thus waiting their turn to take action.

It is highly advisable to use the operating system built-in method for doing this like my suggestion for Windows. If you don't, you will not have the same level of fairness. Most operating systems have built in optimizations for this while the STL objects may not.

Edit: I some how missed the Linux tag but AlexBG provided the link to POSIX built in mutex usage: https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

Upvotes: 1

AlexBG
AlexBG

Reputation: 421

You can use conditions variables from POSIX pthreads if you need pure C. https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

Upvotes: 2

LearningC
LearningC

Reputation: 3162

Search for thread synchronization.
global variables will be shared by threads so use a global variable and then can acquire lock using that variable.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

For this you can use e.g. condition variables, where you can notify all waiting threads.

Upvotes: 2

Related Questions