C Programing Multiple Threads using pthread.h [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to learning C Programing and multiple threads. I started programing some basic stuff [like the following], but I got stuck. Can someone give me a hand?
program.c
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 4
void *main_thread(void *threadID) {
long tid;
tid = (long)threadID;
printf("main thread #%ld!\n", tid);
pthread_exit(NULL);
}
void *first_thread(void *threadID) {
long tid;
tid = (long)threadID;
printf("first thread #%ld!\n", tid);
pthread_exit(NULL);
}
void *second_thread(void *threadID) {
long tid;
tid = (long)threadID;
printf("second thread #%ld!\n", tid);
pthread_exit(NULL);
}
void *last_thread(void *threadID) {
long tid;
tid = (long)threadID;
printf("last thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t=0; t < NUM_THREADS; t++) {
printf("In main Function creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, first_thread, (void *)t);
if (rc) {
printf("ERROR; Return code from pthread_create is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
return 0;
}
I will keep updating the codes above as i figure new things out
*Hey guys. i did not compile it properly but now i figured out.
gcc -pthread -o main main.c

This code will calculate the value of e^x by calculating terms of its series ,
in each term we need to calculate power of a number(in this program it is x) and factorial of each corresponding power.
since these two calculations are independent so we make two threads for these two functions that will be run parallel.
after calculating values of these two function (end of these two threads) we need to merge the results (i mean power/factorial) and then we add all these results in another parallel thread which will run after these two threads.
#include<stdio.h>
#include<math.h>
#include<pthread.h>
#include<stdlib.h>
long double x,fact[150],pwr[150],s[1];
int i,term;
void *Power(void *temp)
{
int k;
for(k=0;k<150;k++)
{
pwr[k] = pow(x,k);
//printf("%.2Lf\n",pwr[k]);
}
return pwr;
}
void *Fact(void *temp)
{
long double f;
int j;
fact[0] = 1.0;
for(term=1;term<150;term++)
{
f = 1.0;
for(j=term;j>0;j--)
f = f * j;
fact[term] = f;
//printf("%.2Lf\n",fact[term]);
}
return fact;
}
void *Exp(void *temp)
{
int t;
s[0] = 0;
for(t=0;t<150;t++)
s[0] = s[0] + (pwr[t] / fact[t]);
return s;
}
int main(void)
{
pthread_t thread1,thread2,thread3;
printf("Enter the value of x (between 0 to 100) (for calculating exp(x)) : ");
scanf("%Lf",&x);
printf("\nThreads creating.....\n");
pthread_create(&thread1,NULL,Power,NULL); //calling power function
pthread_create(&thread2,NULL,Fact,NULL); //calling factorial function
printf("Threads created\n");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("Master thread and terminated threads are joining\n");
printf("Result collected in Master thread\n");
pthread_create(&thread3,NULL,Exp,NULL);
pthread_join(thread3,NULL);
printf("\nValue of exp(%.2Lf) is : %Lf\n\n",x,s[0]);
exit(1);
}

Related

i wanna know what's the diffrent between mutex_lock and pthread_join? [duplicate]

This question already has answers here:
Difference between mutex lock and pthread_join
(2 answers)
Closed last year.
What's the difference between mutex_lock and pthread_join in these two source codes? They seem both to do the same thing, making the main function wait for the thread to finish execution.
This code:
#include "philo.h"
typedef struct s_bablo
{
pthread_mutex_t mutex;
} t_bablo;
void *myturn(void *arg)
{
t_bablo *bablo = (t_bablo *)arg;
int i = 0;
while(i < 10)
{
printf("My Turn ! %d\n", i);
i++;
sleep(1);
}
pthread_mutex_unlock(&bablo->mutex);
}
void *yourturn()
{
int i = 0;
while(i < 5)
{
printf("Your Turn ! %d\n", i);
i++;
sleep(1);
}
}
int main ()
{
t_bablo bablo;
pthread_mutex_init(&bablo.mutex, NULL);
pthread_t ph;
pthread_mutex_lock(&bablo.mutex);
pthread_create(&ph, NULL, myturn, &bablo);
yourturn();
pthread_mutex_lock(&bablo.mutex);
}
And this code :
#include "philo.h"
void *myturn(void *arg)
{
int i = 0;
while(i < 10)
{
printf("My Turn ! %d\n", i);
i++;
sleep(1);
}
}
void *yourturn()
{
int i = 0;
while(i < 5)
{
printf("Your Turn ! %d\n", i);
i++;
sleep(1);
}
}
int main ()
{
pthread_t ph;
pthread_create(&ph, NULL, myturn, NULL);
yourturn();
pthread_join(ph, NULL);
}
not to be rude but you can easily find the difference by googling both functions name...
Though pthread_mutex_lock is for variables. It locks this variable for the current running thread. Thus no other thread can use it, they have to wait for pthread_mutex_unlock to use it.
pthread_join waits for the specified thread to finish it's execution before continuing
I encourage you to read the man pages, they are really self explanatory.

Thread Program on Linux (Posix Thread)

I want to modify the multithread program on the Linux operating system using this Pthread API.
#include <pthread.h>
#include <stdio.h>
int sum;
void *runner(void *param);
int main(int argc, char *argv[]) {
pthread_t tid
pthread_attr_t attr;
if (argc != 2) {
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "%d must be >=0\n", atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, argv[1]);
pthread_join(tid, NULL);
printf("sum = %d\n", sum);
}
void *runner(void *param);
{
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread exit(0);
}
I want to change that program into a program that has 2 threads that work together to add a number. But i don't know how to change it, Thanks again for any help that can be offered. I am sorry,because I'm not good at explaining.
first there is 3 errors : the pthread tid declaration has no ";", then there is one at the end of your runner()* function declaration, and last but not least, a underscore is missing on the last line pthread_exit(0)
beware ahah
ok for vars :
pthread_t tid;
pthread_t tid2;
pthread_attr_t attr;
pthread_attr_t attr2;
and in the code after the ifs, add this :
pthread_attr_init(&attr);
pthread_attr_init(&attr2);
pthread_create(&tid, &attr, runner, argv[1]);
pthread_create(&tid2, &attr2, runner, argv[2]); // not sure for argv[2]?
not sure for argv[2], it depends if it's 2 different numbers?
pthread_join are no use, they are here only for pausing threads, i think that if you want them to work in parallel, you need to only do "pthread_create" and they should work in parallel (but was i saw on my CS class on parallel programming 3 years ago, it will never be "real real" parallel because only the OS can control this and you need to be some kind of a super root to be able to really control the threads
I mean
it won't be faster because it will not be real parallel prog
I'm not exactly sure what you want, but a really quick and dirty solution based on the existing code is below. I'm assuming you just want two thread to sum a single variable to the input.
An explanation of what's going on: I had to fix some minor syntax issues you have in your code, one big one being the semicolon at the end of the runner function definition. I added a mutex to define a critical section in the runner's for loop. It makes sure only 1 thread can update the sum. I'm assuming you want the sum to equal the input, so we just increment it by 1 and check before incrementing whether the value is still below. Like I said, it's quite quick and dirty, not really the ideal solution. To create two threads, we just call the thread create function twice in main.
See https://computing.llnl.gov/tutorials/pthreads/#Mutexes for more important about mutexes and the pthread library.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int sum = 0; // set it once globally
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void *runner(void *param);
int main(int argc, char *argv[]) {
pthread_t tid1, tid2;
pthread_attr_t attr;
if (argc != 2) {
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "%d must be >=0\n", atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);
pthread_create(&tid1, &attr, runner, argv[1]);
pthread_create(&tid2, &attr, runner, argv[1]);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("sum = %d\n", sum);
}
void *runner(void *param) {
int i, upper = atoi(param);
// sum = 0;
int t = pthread_self();
for (i = 1; i <= upper; i++) {
pthread_mutex_lock(&mtx);
if (sum < upper) {
printf("%d incrementing\n", t);
sum += 1;
}
pthread_mutex_unlock(&mtx);
}
pthread_exit(0);
}
Compile with cc -o main main.c -pthread.

Real time task (periodic task)

Good evening everyone,
I'm still learning real-time programming, and I'm trying to synchronize two threads using semaphores, the first thread calculates the sum and returns a value (sum). the sum will be passed as a parameter to the 2nd thread that will use it to calculate an average (this is just an example for manipulating semaphores). my problem now and that the two tasks are not periodic because once the thread returns a result it leaves the loop while and the main() finishes the work !!! now how to make the tasks period ?? thank you for helping me and here is my source code.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t evt;
//first task
void *tache1(void *arg)
{
int j;
int s=0;
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
while(1){
printf("first THREADDDDDDDDD \n");
for(j=0; j<100; j++)
s= s + j;
return (void*) s;
sem_post(&evt);
sleep(3);
}
}
//second task
void *tache2(void *arg){
int moyenne = 1;
int sum = *((int*) arg);
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
while(3){
sem_wait(&evt);
printf("second THREADDDDDDDDD \n");
moyenne= sum/10;
return(void*)moyenne;
sleep(2);
}
}
int main()
{
pthread_t th1, th2;
int sum;
int moyenne;
int status;
sem_init(&evt, 0,0);
printf("start main\n") ;
pthread_create(&th1, NULL, tache1, NULL);
pthread_join(th1, (void*) &sum);
pthread_create(&th2, NULL, tache2, &sum);
pthread_join(th2, (void*) &moyenne);
printf("the sum in the main is %d.\n", sum);
printf("AVG %d.\n", moyenne);
printf("End main\n") ;
return 0;
}
When you do this:
pthread_create(&th1, NULL, tache1, NULL);
pthread_join(th1, (void*) &sum);
pthread_create(&th2, NULL, tache2, &sum);
pthread_join(th2, (void*) &moyenne);
You start a thread, wait for it to finish, then start another thread, then wait for that to finish. That's not multithreading. You want both threads to be active at the same time.
Also, both of your thread functions include a return statement with more statements after them. Once a return statement is hit, the entire function returns immediately. No statements after them are executed. Note also that you don't need a while (1) (or while (3)) loop in either of these functions.
The idea behind semaphores (and mutexes) is that multiple threads are running at once, and both thread need to operate on global data so one thread needs to wait for the other thread to do something before it can access the global data.
So make sum and moyenne global variables, start both threads at once, and get rid of the extra loops in the thread functions.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t evt;
int sum;
int moyenne;
void *tache1(void *arg)
{
int j;
int s=0;
printf("first THREADDDDDDDDD \n");
for(j=0; j<100; j++)
s= s + j;
sum = s;
sem_post(&evt);
return NULL;
}
void *tache2(void *arg)
{
sem_wait(&evt);
printf("second THREADDDDDDDDD \n");
moyenne= sum/10;
return NULL;
}
int main()
{
pthread_t th1, th2;
sem_init(&evt, 0,0);
printf("start main\n") ;
pthread_create(&th1, NULL, tache1, NULL);
pthread_create(&th2, NULL, tache2, NULL);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
printf("the sum in the main is %d.\n", sum);
printf("AVG %d.\n", moyenne);
printf("End main\n") ;
return 0;
}

Synchronizing screen output with mutex and pthread

I'm playing with a fairly simple C example. The program creates two threads and starts them in parallel. Each thread is designed to modify a global variable using a Mutex, and print out the value.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int A=10;
pthread_mutex_t M;
void *codice_Th1(void *arg) {
int i;
for (i=0; i<10;i++){
pthread_mutex_lock(&M);
printf("Thread %s: ", (char *)arg);
A++;
printf("A = %d \n", A);
pthread_mutex_unlock(&M);
sleep(1);
}
pthread_exit(0);
}
void *codice_Th2(void *arg) {
int i;
for (i=0; i<10;i++){
pthread_mutex_lock(&M);
printf("Thread %s: ", (char *)arg);
A--;
printf("A = %d \n", A);
pthread_mutex_unlock(&M);
sleep(1);
}
pthread_exit(0);
}
The main() simply creates the thread, and join the main thread with thread 1 and 2.
int main(){
pthread_t th1, th2;
...
}
What bothers me, is that I get the following output
Thread th1: Thread th2: A = 11
A = 10
Thread th1: A = 11
Thread th2: A = 10
Thread th1: Thread th2: A = 11
A = 10
Thread th1: Thread th2: A = 11
A = 10
Thread th2: Thread th1: A = 9
A = 10
Thread th1: A = 11
Thread th2: A = 10
whereas I would expect every line to execute the printf statements in sequence, given they are inside a mutex.
In other words, I can't understand the ouput
Thread th2: Thread th1: A = 9
I would expect always something similar to
Thread NAME: A = VALUE
Am I missing something?
Never mind, I believe I found the issue. I did not initialize the Mutex with pthread_mutex_init(&M, NULL); before using it.
Setting
int main(){
pthread_t th1, th2;
int ret;
pthread_mutex_init(&M, NULL);
fixed the issue. I assume using pthread_mutex_init is a requirement. Unfortunately, skipping the mutex initialization din't produce any warning or error. The script silently compiled.

UNIX Pthreads & mutex; program locks up

Following scenario:
We are supposed to make x Threads maximum. Our main-function is supposed to make a single new thread with a pointer to the function 'makeThreads'. This function is supposed to make up to 2 threads, depending on how many threads are already there. Race conditions are to avoid.
I'm stuck. I'm not exactly sure how to solve the problem I'm running into, partly because I don't can't identify the problem itself.
Suggestions are greatly appreciated!
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#define MAX_THR 20
pthread_mutex_t mutex;
int threadCount = 0;
int randomNbr(){
int number = (rand() % 10) + 1;
return number;
}
void *makeThreads(void* number){
int rndnmb = *((int *) number);
pthread_mutex_lock(&mutex);
sleep(rndnmb);
pthread_t threadDummy;
int thread1, i, threadID, rndnbr;
threadID = threadCount;
printf("Hello from Thread %d!\n", threadID);
for(i = 0; i < 2; i++){
if(threadCount < MAX_THR){
rndnbr = randomNbr();
int *rnd = &rndnbr;
threadCount++;
thread1 = pthread_create(&threadDummy, NULL, *makeThreads, (void *) rnd);
pthread_join(threadDummy, NULL);
}
}
pthread_mutex_unlock(&mutex);
printf("Goodbye from Thread %d!\n", threadID);
}
int main(){
int t1, rndnbr;
pthread_t threadOne;
pthread_mutex_init(&mutex, NULL);
srand(time(NULL));
rndnbr = randomNbr();
int *rnd = &rndnbr;
threadCount++;
t1 = pthread_create(&threadOne, NULL, *makeThreads, (void *) rnd);
pthread_join(threadOne, NULL);
}

Resources