Mutex and order of execution - c

First of all I am still new to posix programming and still understanding basic concepts. It is still not very clear for me how do pthread_mutex_lock
pthread_mutex_unlock do work.
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#inlcude <stdio.h>
pthread_mutex_t_mtx;
void* routine(void* i){
int j;
for(j = 0; j < 1000000; ++j){
pthread_mutex_lock(&mtx);
printf("Inside thread %d\n", i);
pthread_mutex_unlock(&mtx);
}
return NULL;
}
int main()
{
pthread_t th[3];
int i;
pthread_mutex_init(&mtx, NULL);
for(i = 1; i <= 2; ++i)
{
if(pthread_create(th + i, NULL, routine, i){
perror(NULL); return 1;
}
}
for(i = 1; i <=2; ++i)
pthread_join(th[i], NULL);
return 0;
}
What should be the correct output of the above program ? I think that because of the lock and unlock of the mutex there would be 2000000 iterations, but it is not very clear for me the order that they are done in. Does the first thread execute the first 1000000 steps of the for? Does it even execute the first one of the 20000000 ? Or does this happen by a more chaotic order?

Assuming that the mutex is a global one, you will get 2000000 messages, with 1000000 from each thread. The order of those is random, however they will not interfere each other as each print is protected by the mutex
EDIT: I just noticed, that you are joining before creating the next thread. Therfore first there will be all messages of the first, then of the second thread. In this case the mutex has no effect at all. The reason for the ordering is simply that you will not have more then one worker-thread running at the same time.

Related

C/Linux: Alternating between threads

So I have this code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <semaphore.h>
#define nr_threads 3
sem_t semaphores[nr_threads];
typedef struct {
int id;
char *word;
}th_struct;
void *thread_function(void *arg)
{
th_struct *th_data = (th_struct *) arg;
sem_wait(&semaphores[th_data->id]);
printf("[thread#%d] %s\n", th_data->id, th_data->word);
sem_post(&semaphores[th_data->id + 1]);
return NULL;
}
int main(int argc, char **argv)
{
pthread_t tid[nr_threads];
th_struct th_data[nr_threads];
for(int i = 0; i < nr_threads; i++){
if (sem_init(&semaphores[i], 0, 1) != 0){
perror("Could not init semaphore");
return -1;
}
}
sem_post(&semaphores[0]);
for(int i = 0; i < nr_threads; i++){
th_data[i].id = i;
th_data[i].word = argv[i + 1];
pthread_create(&tid[i], NULL, thread_function, &th_data[i]);
}
for(int i = 0; i < nr_threads; i++){
pthread_join(tid[i], NULL);
}
for(int i = 0; i < nr_threads; i++)
sem_destroy(&semaphores[i]);
return 0;
}
I give from the command line 3 words, for example "one two three", and each thread prints one word, synchronized, so that the order will be always correct. I'm new to threads and semaphores, and my brain is currently used to sem_wait(sem) and after sem_post(sem), where sem is the same semaphore. What I'm asking is a complete explanation on why this code works and how it works. Why the semaphores are initialized with 0 permissions? Why there is sem_post(first_semaphore)? I'm very confused.
First of all, there's a bug in that code...
After it has done its job, each thread unconditionally calls sem_post() on the semaphore of the next thread. Therefore, the third thread will try to access semaphores[3] which doesn't exist.
Now what's going on (assuming the bug wasn't there) is this:
3 semaphores are created and initialized so that they are locked immediately
3 threads are created, each calling sem_wait() and blocking (because the semaphores are initialized to 0)
After a thread has done it's job, it calls sem_post() on the semaphore of the next one, which then returns from sem_wait()
This is the basic idea, but to get it running, someone needs to call sem_post() for the first semaphore. So that's why there is that sem_post(&semaphores[0]) in main().
Note: This is more of a long comment, not a complete answer.
I like to think of a semaphore as a blocking queue of informationless tokens. The semaphore's count is the number of tokens in the queue.
From that viewpoint, the main thread in your program creates a single token (from nothing, because the token is nothing), and it hands the token to the first worker thread by calling sem_post(&semaphores[0]);.
The first worker is able to do its job after taking the token from its input queue (i.e., when sem_wait(&semaphores[th_data->id]); returns. And after it has finished its work, it hands the token to the next thread: sem_post(&semaphores[th_data->id + 1]);

I would like to get 4 separate prints: "This is a thread 1", "This is a thread 2" and so on

pthread_create in a for loop, this is my code
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
pthread_mutex_t mutex;
void* helloWorld(void *i) {
pthread_mutex_lock(&mutex);
printf("This is a thread %d\n", *((int*) i));
pthread_mutex_unlock(&mutex);
return 0;
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_t threads[4];
int i;
printf("Main Message\n");
for (i = 0; i < 4; i++) {
pthread_create(&threads[i], NULL, helloWorld, &i);
}
for (i = 0; i < 4; i++) {
pthread_join(threads[i], NULL);\
}
pthread_mutex_destroy(&mutex);
return 0;
}
The order doesn't really matter as long as all 4 threads are working.
I've tried to use mutex but it didn't solve the issue.
My current output is pretty random, it can be 0000 or 0112 or anything else.
The problem is two-fold:
First of all you don't have control over when the threads run or in which order.
You pass the same pointer to all threads.
You can solve the second issue by passing the value if i to the threads. This is one of the few cases where it's considered okay to pass values instead of pointers:
pthread_create(&threads[i], NULL, helloWorld, (void*)(uintptr_t) i);
Then in the thread
printf("This is a thread %d\n", (int)(uintptr_t) i);
The first issue, about the order, you have to come up with some other way to synchronize the threads and how they notify each other. For example by using four condition signals, one for each thread, that you signal in the order you want the threads to execute.

Testing race condition

I just started learning about thread today, and wanted to test the race condition of threads by running two codes with/without mutex.
#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#define NTHREADS 3
#define ITERATIONS (long long) 1000000000
//pthread_mutex_t mutex;
static long long counter = 0;
static void * thread_f(void * arg) {
unsigned long long i;
(void)arg;
for (i = 0; i != ITERATIONS; i++) {
// pthread_mutex_lock(&mutex);
counter = counter + 1;
// pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void) {
pthread_t threads[NTHREADS];
int i;
for (i = 0; i != NTHREADS; i++)
pthread_create(&threads[i], NULL, thread_f, NULL);
for (i = 0; i != NTHREADS; i++)
pthread_join(threads[i], NULL);
printf("expected = %lld, actual = %lld\n", NTHREADS*ITERATIONS, counter);
printf("experienced %lld race conditions\n", NTHREADS*ITERATIONS - counter);
system("pause");
return 0;
}
So, without mutex, the program prints out these following lines on cmd:
expected = 3000000000, actual = 1174158414
experienced 1825841586 race conditions
However, if I put mutex in the code, and run the program, cmd pops up then shuts down itself without showing any result.
I want to know if I coded anything wrong or is misusing mutex lines as I really don't know much about threads.
p.s this is coded in windows 10, using visual studio
Thanks to EOF from the comment, I found out that I did not initialize mutex in the code.
I simply added:
if (pthread_mutex_init(&mutex, NULL)) {
printf("Something went wrong\n");
return 1;
}
this in the main, and everything works fine now.

C - synchronizing multiple threads w/ mutexs

I'm trying to synchronize multiple (7) threads. I thought I understood how they work until I was trying it on my code and my threads were still printing out of order. Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
void *text(void *arg);
long code[] = {4,6,3,1,5,0,2}; //Order in which to start threads
int num = 0;
pthread_mutex_t lock; //Mutex variable
int main()
{
int i;
pthread_t tid[7];
//Check if mutex worked
if (pthread_mutex_init(&lock, NULL) != 0){
printf("Mutex init failed\n");
return 1;
}
//Initialize random number generator
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
//Create our threads
for (i=0; i<7; i++)
pthread_create(&tid[i], NULL, text, (void*)code[i]);
//Wait for threads to finish
for (i=0; i<7; i++){
if(pthread_join(tid[i], NULL)){
printf("A thread failed to join\n");
}
}
//Destroy mutex
pthread_mutex_destroy(&lock);
//Exit main
return 0;
}
void *text (void *arg)
{
//pthread_mutex_lock(&lock); //lock
long n = (long) arg;
int rand_sec = rand() % (3 - 1 + 1) + 1; //Random num seconds to sleep
while (num != n) {} //Busy wait used to wait for our turn
num++; //Let next thread go
sleep(rand_sec); //Sleep for random amount of time
pthread_mutex_lock(&lock); //lock
printf("This is thread %d.\n", n);
pthread_mutex_unlock(&lock); //unlock
//Exit thread
pthread_exit(0);
}
So here I am trying to make threads 0-6 print IN ORDER but right now they are still scrambled. The commented out mutex lock is where I originally had it, but then moved it down to the line above the print statement but I'm having similar results. I am not sure where the error in my mutex's are, could someone give a hint or point me in the right direction? I really appreciate it. Thanks in advance!
You cannot make threads to run in order with only a mutex because they go in execution in an unpredictable order.
In my approach I use a condition variable and a shared integer variable to create a queueing system. Each thread takes a number and when the current_n number is equal to the one of the actual thread, it enters the critical section and prints its number.
#include <pthread.h>
#include <stdio.h>
#define N_THREAD 7
int current_n = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t number = PTHREAD_COND_INITIALIZER;
void *text (void *arg) {
int i = (int)arg;
pthread_mutex_lock(&mutex);
while ( i > current_n ) {
pthread_cond_wait(&number, &mutex);
}
//i = current_n at this point
/*I use stderr because is not buffered and the output will be printed immediately.
Alternatively you can use printf and then fflush(stdout).
*/
fprintf(stderr, "I'm thread n=%d\n", i);
current_n ++;
pthread_cond_broadcast(&number);
pthread_mutex_unlock(&mutex);
return (void*)0;
}
int main() {
pthread_t tid[N_THREAD];
int i = 0;
for(i = 0; i < N_THREAD; i++) {
pthread_create(&tid[i], NULL, text, (void *)i);
}
for(i = 0; i < N_THREAD; i++) {
if(pthread_join(tid[i], NULL)) {
fprintf(stderr, "A thread failed to join\n");
}
}
return 0;
}
The output is:
I'm thread n=0
I'm thread n=1
I'm thread n=2
I'm thread n=3
I'm thread n=4
I'm thread n=5
I'm thread n=6
Compile with
gcc -Wall -Wextra -O2 test.c -o test -lpthread
Don't worry about the warnings.

Multithreaded semaphore program

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;
}
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.

Resources