Two threads printing char - c

I have to wriete program
"Bring to life two threads. First thread must write char 'a' 30000
times second one 'b' 25000 times.
I wrote this program but i do not know this is a good result. I expect first see 30000 times a then b when I use pthread_join(p,NULL). My program write a and b randomaly it is good or not?
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t f,s;
void* a(void *arg)
{
int j;
for(j=0;j<30000;j++) printf("a\n");
return NULL;
}
void* b(void *arg)
{
int u;
for(u=0;u<25000;u++) printf("b\n");
return NULL;
}
int main(void)
{
int i = 0;
int err;
err = pthread_create(&f, NULL, &a, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
err = pthread_create(&s, NULL, &b, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
pthread_join(f, NULL);
sleep(5);
return 0;
}

Related

Use semaphores in C to protect variable within for loop

I'm trying to use semaphores to avoid that a global variable is changed by threads and this variable is supposed to increment within the for loop. My main objective is to protect the variable cnt from the threads so it can increment within the for loop. However, I don't know how to do it because this is the first time I work with semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
sem_t semaphore;
int cnt = 0; //global shared variable
void *threadProd(void *param); //threads call this function.
int main(int argc, char *argv[])
{
int niters;
pthread_t tid1, tid2; //thread ids
sem_init(&semaphore,0,1);
if (argc != 2){
printf("Usage: %s <niters>\n", argv[0]);
exit(0);
}
niters = atoi(argv[1]);
pthread_create(&tid1, NULL, threadProd, &niters);
pthread_create(&tid2, NULL, threadProd, &niters);
pthread_join(tid1, NULL); //wait for thread to finish
pthread_join(tid2, NULL);
//check answer:
if(cnt != (2 * niters))
printf("Incorrect answer, cnt = %d\n", cnt);
else
printf("Correct answer, cnt = %d\n", cnt);
sem_destroy(&semaphore);
exit(0);
}
//Thread routine
void *threadProd(void *vargp)
{
sem_wait(&semaphore);
int upper = *((int *) vargp);
for (int i = 0; i < upper; i++)
cnt ++;
sem_post(&semaphore);
return NULL;
}

How to implement futex_wait sysccall for pid

I have a code which puts threads to sleep using futex_wait syscall. how can i put a process to sleep using futex_wait syscall?
I understand this program, it creates the thread and put them on sleep and then calls the futex_Wake syscall to wake the thread and futex_wake should return the number of threads it has woken up
Sample Code:
#include <stdio.h>
#include <pthread.h>
#include <linux/futex.h>
#include <syscall.h>
#include <unistd.h>
#define NUM 2
int futex_addr;
int futex_wait(void* addr, int val1){
return syscall(SYS_futex,&futex_addr,val1, NULL, NULL, 0);
}
int futex_wake(void* addr, int n){
int msecs = 0;
int waked = 0;
while(1){
sleep(1);
msecs++;
waked = syscall(SYS_futex, addr, FUTEX_WAKE, n, NULL, NULL, 0);
if (waked == n)
break;
if (msecs > 100){
printf("Wake timedout\n");
return 0;
}
}
return waked;
}
void* thread_f(void* par) {
int id = (int) par;
/*go to sleep*/
futex_addr = 0;
int ret = futex_wait(&futex_addr,0);
printf("Futex_wait_returned %d\n", ret);
// printf("Thread %d starting to work!\n",id);
return NULL;
}
int main () {
pthread_t threads[NUM];
int i;
for (i=0;i<NUM;i++) {
pthread_create(&threads[i],NULL,thread_f,(void *)i);
}
printf("Everyone wait...\n");
sleep(1);
printf("Now go!\n");
/*wake threads*/
int ret = futex_wake(&futex_addr, NUM);
printf("No of futex_wake processes are %d\n", ret);
/*give the threads time to complete their tasks*/
sleep(1);
printf("Main is quitting...\n");
return 0;
}
I am quite new to it, so i want to understand what changes should i make to put a process to sleep using futex

Program with multiple threads always giving same output

I'm learning multi-threading and trying to create a program that can print two strings alternately.
I have written the following code :
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t lock;
void print(char a[50]){
pthread_mutex_lock(&lock);
printf("%s", a); //output console is the shared resource
sleep(2);
pthread_mutex_unlock(&lock);
}
void* hello(void* status){
while(*((char*)status) != '\n'){
print("Hello World\n");
}
}
void* bye(void* status){
while(*((char*)status) != '\n'){
print("Goodbye World\n");
}
}
int main(){
pthread_t id1, id2;
char status = '\0';
int state;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init has failed\n");
exit(1);
}
printf("Starting Threads (Press Enter to terminate)\n");
state = pthread_create(&id1, NULL, hello, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
state = pthread_create(&id2, NULL, bye, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
scanf("%c", &status);
printf("Out of The Threads\n");
pthread_mutex_destroy(&lock);
return 0;
}
According to what I understand, the mutex should lock the print function once for the hello function and then for the bye function. But I only get this output:
Starting Threads (Press Enter to terminate)
Hello World
Hello World
Hello World
Hello World
Hello World
Why does only the hello function get allocated the print function? How do I get it do print both?
Because, you use infinitive while in each function hello and bye. When the first thread starts, it never exits the while loop unless you press enter.
But when you type enter, the loop conditions in all functions will be false, so two threads will never touch print function again.
OT, you forget to join the threads.
Try to delete the while loop in each function and use it in main function, and see what happen. For example the program below (it may be not optimized, but i just want to show why your program always print Hello World:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t lock;
void print(char a[50]){
pthread_mutex_lock(&lock);
printf("%s", a); //output console is the shared resource
sleep(2);
pthread_mutex_unlock(&lock);
}
void* hello(void* status){
// while(*((char*)status) != '\n'){
print("Hello World\n");
//}
}
void* bye(void* status){
//while(*((char*)status) != '\n'){
print("Goodbye World\n");
// }
}
int main(){
pthread_t id1, id2;
char status = '\0';
int state;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init has failed\n");
exit(1);
}
printf("Starting Threads (Press Enter to terminate)\n");
while(status != '\n') {
state = pthread_create(&id1, NULL, hello, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
state = pthread_create(&id2, NULL, bye, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
pthread_join(id1, NULL);
pthread_join(id1, NULL);
scanf("%c", &status);
}
printf("Out of The Threads\n");
pthread_mutex_destroy(&lock);
return 0;
}

POSIX threads and keys

I need to create two private keys and two threads and then I need to make these threads "exchange" keys
I already created the keys and initialized them and I can also print their value, but I do not know how to make them exchange keys. Maybe someone will tell you something. maybe for this I need to call the same thread several times, but I also don’t know how to do this. I do not ask you to give me a ready-made program, maybe just some little hint or advice
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_key_t key, key2;
void get_data()
{
int *x = (int*)pthread_getspecific(key2);
if(x == NULL)
printf("The value is NULL\n");
else
printf("Key value is %d\n", *x);
}
void get_data2()
{
int *x = (int*)pthread_getspecific(key);
if(x == NULL)
printf("The value is NULL\n");
else
printf("Key value is %d\n", *x);
}
void *func(void *data)
{
int *num;
int *x;
printf("Thread №%ld\n", pthread_self());
num = (int*)data;
get_data();
pthread_setspecific(key, (void*)num);
get_data();
}
void *func2(void *data)
{
int *num;
int *x;
printf("Thread №%ld\n", pthread_self());
num = (int*)data;
get_data2();
pthread_setspecific(key2, (void*)num);
get_data2();
}
int main()
{
int ret_code, type = 3;
pthread_t th, th2;
ret_code = pthread_key_create(&key, NULL);
if(ret_code != 0)
fprintf(stderr, "ptrhead_key_create() error %d\n", ret_code);
ret_code = pthread_key_create(&key2, NULL);
if(ret_code != 0)
fprintf(stderr, "ptrhead_key_create() error %d\n", ret_code);
printf("type: %d\n", type);
ret_code = pthread_create(&th, NULL, func, (void*)&type);
if(ret_code != 0)
fprintf(stderr, "pthread_create() error %d\n", ret_code);
sleep(1);
type = 10;
printf("type: %d\n", type);
ret_code = pthread_create(&th2, NULL, func2, (void*)&type);
if(ret_code != 0)
fprintf(stderr, "pthread_create() error %d\n", ret_code);
ret_code = pthread_join(th, NULL);
ret_code = pthread_join(th2, NULL);
}

creating threads using pthread.c

I am trying to learn how to create threads in c using the pthread library, I am using the following code:
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
static int glob = 0;
static sem_t sem;
static void *threadFunc(void *arg) {
int loops = *((int *) arg);
int loc, j;
for (j = 0; j < loops; j++) {
if (sem_wait(&sem) == -1)
exit(2);
loc = glob;
loc++;
glob = loc;
if (sem_post(&sem) == -1)
exit(2);
}
printf("\n%d %d\n",glob/20,glob);
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t t1, t2, t3, t4;
int s;
int loops = 20;
if (sem_init(&sem, 0, 1) == -1) {
printf("Error, init semaphore\n");
exit(1);
}
s = pthread_create(&t1, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_create(&t2, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_create(&t3, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_create(&t4, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t1, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t2, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t3, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t4, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
printf("glob value %d \n", glob);
exit(0);
}
What are the expected values of glob when I try to print them using the print statement in threadFunc? Shuold they be 20,40,60 and 80? When I execute the above program I get different values for glob like, 61, 50, 73 and 80!! or 29,76,78,80? How come? EVerytime I execute I get different values for glob. I think it has something to do with the semaphore but then how can the value for glob decrease like in the first output example I gave you?
Furthermore, what is the purpose for a thread_initiate given to pthread_create? Not threadFunc specifically but in general what do programmers dealing with threads in c generally do using the thread_initiate function passed to pthread_create?
I figured it out, I didn't think about the code properly. The threads are running concurrently so there is no way to decide what the value of glob will be. If two threads are running, the first one might be 5 values into the loop and the second thread might be 2 values which will mean the value of glob is 7. When glob is printed the value will always be greater than a multiple of 20 (for this particular problem).
As for the second part I believe that the starting routine is the code that the thread is going to run.
Thanks to #WhozCraig and #JoachimPileborg for the help!

Resources