threads with different priority levels - pthreads

I am trying to make two threads (t1 and t2) each with a different priority level (priority1 and priority2).
t1 runs First_thread() and t2 runs Second_thread(). Each job is simply running a counter.
The program shows no error but when I try to execute; the message says:
Thread 1 cannot run
The code is:
pthread_attr_t attr1;
struct sched_param priority1;
pthread_attr_t attr2;
struct sched_param priority2;
pthread_attr_init(&attr1);
pthread_attr_setinheritsched(&attr1, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr1, SCHED_FIFO);
priority1.sched_priority = 10;
pthread_attr_setschedparam(&attr1, &priority1);
pthread_attr_init(&attr2);
pthread_attr_setinheritsched(&attr2, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr2, SCHED_FIFO);
priority2.sched_priority = 9;
pthread_attr_setschedparam(&attr2, &priority2);
if (pthread_create(&t1, &attr1, First_thread, NULL)) {
printf("ERROR CANNOT START First Thread\n");
return 0;
}
if (pthread_create(&t2, &attr2, Second_thread, NULL)){
printf("ERROR CANNOT START First Thread\n");
return 0;
}
pthread_join(t1, NULL);
pthread_attr_destroy(&attr1);
pthread_join(t2, NULL);
pthread_attr_destroy(&attr2);

Related

Should we use mutex with semaphore to make a correct synchronization and to prevent a race condition?

I am trying to see the race condition happens in the comsumer-producser problem,
so I made multiple producers and mulitple consumers.
From what I know that I need to provide mutex with semaphore:
Mutex for the race conditions, because muliple producers can access the buffer at the same time. then the data might be corrupted.
And semaphore to provide signaling between the producers and the consumers
The problem here that the sync is happening correctly while I am not using the Mutex (i am using the Semaphore only). is my understanding correct or is there anything wrong to do in the code below:
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
int buffer;
int loops = 0;
sem_t empty;
sem_t full;
sem_t mutex; //Adding MUTEX
void put(int value) {
buffer = value;
}
int get() {
int b = buffer;
return b;
}
void *producer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
sem_wait(&empty);
//sem_wait(&mutex);
put(i);
//printf("Data Set from %s, Data=%d\n", (char*) arg, i);
//sem_post(&mutex);
sem_post(&full);
}
}
void *consumer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
sem_wait(&full);
//sem_wait(&mutex);
int b = get();
//printf("Data recieved from %s, %d\n", (char*) arg, b);
printf("%d\n", b);
//sem_post(&mutex);
sem_post(&empty);
}
}
int main(int argc, char *argv[])
{
if(argc < 2 ){
printf("Needs 2nd arg for loop count variable.\n");
return 1;
}
loops = atoi(argv[1]);
sem_init(&empty, 0, 1);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
pthread_t pThreads[3];
pthread_t cThreads[3];
pthread_create(&cThreads[0], 0, consumer, (void*)"Consumer1");
pthread_create(&cThreads[1], 0, consumer, (void*)"Consumer2");
pthread_create(&cThreads[2], 0, consumer, (void*)"Consumer3");
//Passing the name of the thread as paramter, Ignore attr
pthread_create(&pThreads[0], 0, producer, (void*)"Producer1");
pthread_create(&pThreads[1], 0, producer, (void*)"Producer2");
pthread_create(&pThreads[2], 0, producer, (void*)"Producer3");
pthread_join(pThreads[0], NULL);
pthread_join(pThreads[1], NULL);
pthread_join(pThreads[2], NULL);
pthread_join(cThreads[0], NULL);
pthread_join(cThreads[1], NULL);
pthread_join(cThreads[2], NULL);
return 0;
}
I believe I have the problem figured out. Here's what is happening
When initializing your semaphores you set empty's number of threads to 1 and full's to 0
sem_init(&empty, 0, 1);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
This means that there is only one "space" for the thread to get into the critical region. In other words, what your program is doing is
produce (empty is now 0, full has 1)
consume (full is now 0, empty has 0)
produce (empty is now 0, full has 1)
...
It's as if you had a token (or, if you like, a mutex), and you pass that token between consumers and producers. That is actually what the consumer-producer problem is all about, only that in most cases we are worried about having several consumers and producers working at the same time (which means you have more than one token). Here, because you have only one token, you basically have what one mutex would do.
Hope it helped :)

C Application with Pthread crashes

i have a problem with the pthread library in a C-Application for Linux.
In my Application a Thread is started over and over again.
But I allways wait until the Thread is finished before starting it.
At some point the thread doesn't start anymore and I get an out of memory error.
The solution I found is to do a pthread_join after the thread has finished.
Can anyone tell me why the Thread doesn't end correctly?
Here is an Example Code, that causes the same Problem.
If the pthread_join isn't called the Process stops at about 380 calls of the Thread:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <pthread.h>
#include <unistd.h>
volatile uint8_t check_p1 = 0;
uint32_t stack_start;
void *thread1(void *ch)
{
static int counter = 0;
int i;
int s[100000];
char stack_end;
srand(time(NULL) + counter);
for (i = 0; i < (sizeof (s)/sizeof(int)); i++) //do something
{
s[i] = rand();
}
counter++;
printf("Thread %i finished. Stacksize: %u\n", counter, ((uint32_t) (stack_start)-(uint32_t) (&stack_end)));
check_p1 = 1; // Mark Thread as finished
return 0;
}
int main(int argc, char *argv[])
{
pthread_t p1;
int counter = 0;
stack_start = (uint32_t)&counter; // save the Address of counter
while (1)
{
counter++;
check_p1 = 0;
printf("Start Thread %i\n", counter);
pthread_create(&p1, NULL, thread1, 0);
while (!check_p1) // wait until thread has finished
{
usleep(100);
}
usleep(1000); // wait a little bit to be really sure that the thread is finished
//pthread_join(p1,0); // crash without pthread_join
}
return 0;
}
The solution I found is to do a pthread_join after the thread has finished.
That is the correct solution. You must do that, or you leak thread resources.
Can anyone tell me why the Thread doesn't end correctly?
It does end correctly, but you must join it in order for the thread library to know: "yes, he is really done with this thread; no need to hold resources any longer".
This is exactly the same reason you must use wait (or waitpid, etc.) in this loop:
while (1) {
int status;
pid_t p = fork();
if (p == 0) exit(0); // child
// parent
wait(&status); // without this wait, you will run out of OS resources.
}

Xlib Muti-thread program only works under strace

I'm writing a muti-thread program using xlib, pthread and cairo.
This program create a thread in order to draw ten points after a click event.
The problem is:
After the program drew three points, it got crashed and xlib complaint
X Error of failed request: BadRequest (invalid request code or no such operation)
Major opcode of failed request: 0 ()
Serial number of failed request: 67
Current serial number in output stream: 97
However, it can work properly when I'm using strace like "strace ./a.out".
Here's my code-clips:
void *draw_point(void *arg) { //paint random-postion point
int i = 0;
int seed;
double x ,y;
srand(seed);
cairo_set_source_rgba (cairo, 1, 0.2, 0.2, 0.6);
for(i = 0; i< 10; i++) {
x = rand() % 200;
y = rand() % 200;
if(candraw) {
cairo_arc (cairo, x, y, 10.0, 0, 2*M_PI);
cairo_fill (cairo);
}
hasdraw = true;
sleep(1);
}
return NULL;
}
bool win_main(void)
{
int clickx = 0, clicky = 0;
unsigned long valuemask;
XEvent event;
valuemask = ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask;
XSelectInput(display, win, valuemask);
pthread_t thread;
while (1) {
while (XPending(display) == 0) {
candraw = true;
if(hasdraw)
XFlush(display);
candraw = false;
}
XNextEvent(display, &event);
candraw = false;
switch (event.type) {
case MotionNotify:
//...
break;
case ButtonPress:
clickx = event.xbutton.x;
clicky = event.xbutton.y;
if(clicky < 50)
pthread_create(&thread, NULL, draw_point, NULL);
break;
case ButtonRelease:
//...
break;
default:
break;
}
}
return 0;
}
Does anyone has an idea about this weird problem?
Thanks a lot!
The problem is caused by using multi-threading with the 2 threads trying to access the display at the same.
strace will change the timing, so the threads are accessing the display at different times.
Xlib does have functions to prevent conflict. Lookup XInitThreads, which enables thread support and XLockDisplay and XUnlockDisplay, which you will need to call from each thread before and after accessing the display.

pthread_kill ends calling program

I am working on Ubuntu 12.04.2 LTS. I have a strange problem with pthread_kill(). The following program ends after writing only "Create thread 0!" to standard output. The program ends with exit status 138.
If I uncomment "usleep(1000);" everything executes properly. Why would this happen?
#include <nslib.h>
void *testthread(void *arg);
int main() {
pthread_t tid[10];
int i;
for(i = 0; i < 10; ++i) {
printf("Create thread %d!\n", i);
Pthread_create(&tid[i], testthread, NULL);
//usleep(1000);
Pthread_kill(tid[i], SIGUSR1);
printf("Joining thread %d!\n", i);
Pthread_join(tid[i]);
printf("Joined %d!", i);
}
return 0;
}
void sighandlertest(int sig) {
printf("print\n");
pthread_exit();
//return NULL;
}
void* testthread(void *arg) {
struct sigaction saction;
memset(&saction, 0, sizeof(struct sigaction));
saction.sa_handler = &sighandlertest;
if(sigaction(SIGUSR1, &saction, NULL) != 0 ) {
fprintf(stderr, "Sigaction failed!\n");
}
printf("Starting while...\n");
while(true) {
}
return 0;
}
If the main thread does not sleep a bit before raising the SIGUSR1, the signal handler for the thread created most propably had not been set up, so the default action for receiving the signal applies, which is ending the process.
Using sleep()s to synchronise threads is not recommended as not guaranteed to be reliable. Use other mechanics here. A condition/mutex pair would be suitable.
Declare a global state variable int signalhandlersetup = 0, protect access to it by a mutex, create the thread, make the main thread wait using pthread_cond_wait(), let the created thread set up the signal handle for SIGUSR1, set signalhandlersetup = 0 and then signal the condition the main thread is waiting on using pthread_signal_cond(). Finally let the main thread call pthread_kill() as by your posting.

main() thread versus one created by pthread_create()

I've been creating programs exemplifying concurrency bugs using POSIX threads.
The overall question I have is what is the difference between the main() thread and one created by pthread_create(). My original understanding was that they are pretty much the same but, I'm getting different results from the two programs below.
To expand before showing the code I've written, what I am wondering is: Is there a difference between the following.
int main() {
...
pthread_create(&t1, NULL, worker, NULL);
pthread_create(&t2, NULL, worker, NULL);
...
}
and
int main() {
...
pthread_create(&t1, NULL, worker, NULL);
worker();
...
}
To expand using a full example program. I've made two versions of the same program. They both have the same function worker()
void *worker(void *arg) {
printf("Entered worker function\n");
int myid;
int data = 999;
pthread_mutex_lock(&gidLock);
myid = gid;
gid++;
printf("myid == %d\n", myid);
pthread_mutex_unlock(&gidLock);
if (myid == 0) {
printf("Sleeping since myid == 0\n");
sleep(1);
result = data;
printf("Result updated\n");
}
return NULL;
}
gid and data are globals initialized to 0.
What's the difference between the following main() functions
int main_1() {
pthread_t t1, t2;
int tmp;
/* initialize globals */
gid = 0;
result = 0;
pthread_create(&t1, NULL, worker, NULL);
pthread_create(&t2, NULL, worker, NULL);
pthread_join(t2, NULL);
printf("Parent thread exited worker function\n");
tmp = result;
printf("%d\n", tmp);
pthread_exit((void *) 0);
}
and
int main_2() {
pthread_t t1;
int tmp;
/* initialize globals */
gid = 0;
result = 0;
pthread_create(&t1, NULL, worker, NULL);
worker(NULL);
printf("Parent thread exited worker function\n");
tmp = result;
printf("%d\n", tmp);
pthread_exit((void *) 0);
}
Sample output for main_1()
Entered worker function
myid == 0
Sleeping since myid == 0
Entered worker function
myid == 1
Parent thread exited worker function
0
Result Updated
Sample output for main_2()
Entered worker function
myid == 0
Sleeping since myid == 0
Entered worker function
myid == 1
/* program waits here */
Result updated
Parent thread exited worker function
999
Edit: The program intentionally has a concurrency bug (an atomicity violation). Delays were added by calling sleep() to attempt to force the buggy interleaving to occur. The intention of the program is to be used to test software automatically detecting concurrency bugs.
I would think that main_1() and main_2() are essentially the same program which should result in the same interleaving when run on the same system (or largely the same interleaving; it is indeterminate, but running the same program on the same system only tend explores a small section of the potential scheduling and rarely deviates [1]).
The "desired" output is is that from main_1()
I'm not sure why the thread with myid == 1 stalls and does not return in main_2(). If I had to guess
Thanks for reading this far, and if anyone needs more information I'd be happy to oblige. Here are links to the full source code.
main_1(): https://gist.github.com/2942372
main_2(): https://gist.github.com/2942375
I've been compiling with gcc -pthread -lpthread
Thanks again.
[1] S. Park, S. Lu, Y. Zhou. "CTrigger: Exposing Atomicity Violation Bugs from Their Hiding Places"

Resources