#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void *compute() {
float total;
int i;
float oldtotal =0, result =0;
for(i=0;i<1999999999;i++)
{
result =sqrt(1001.0)*sqrt(1001.0);
}
printf ("Result is %f\n", result);
oldtotal = total;
total = oldtotal + result;
printf("Total is %f\n",total);
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL,compute, NULL);
pthread_create(&thread2, NULL,compute, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Only one thread is created when I run the program. I've checked this using the top command in cmd, the process runs at 197% so I believe two processes are being run. I've remembered to compile it with the -pthreads flag.
197% = 2 threads exercising the cpu doing sqrt() in a loop, plus one thread which is not using any cpu because it is waiting for the other threads to finish in pthread_join().
Related
When I use mutex_lock inside loop, my code spends huge time in execution, and I can't get the output.
I know lock () take time, but not as this!
I have this code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int x = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *fnC()
{
int i;
for (i = 0; i < 2; i++)
{
pthread_mutex_lock(&mutex);
x++;
}
printf(" %d", x);
pthread_mutex_unlock(&mutex);
}
int main()
{
int rt1, rt2;
pthread_t t1, t2;
/* Create two threads */
if ((rt1 = pthread_create(&t1, NULL, &fnC, NULL)))
printf("Thread creation failed: %d\n", rt1);
if ((rt2 = pthread_create(&t2, NULL, &fnC, NULL)))
printf("Thread creation failed: %d\n", rt2);
/* Wait for both threads to finish */
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("\n");
return 0;
}
Anyone can explain this?
I am trying to detect core to core latency in simple memory sharing. My objective is to read a global variable from two different threads. Let's say the variable is x=0 at the beginning. Now one thread will read the value and change the x to 1. Another thread is reading the same variable and as soon as it reads x=1, it makes it 0. I have written the following code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
double getsecs(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec / 1.0e6;
}
int x=0;
//count=0;
void* changetoone(void *arg)
{
//sched_setaffinity(0);
for (int i=0; i<10000; i++){
while(x!=1)
{
x=1;
printf("%d", x);
}
}
return 0;
}
void* changetozero(void *arg){
//sched_setaffinity(5);
for (int i=0; i<10000; i++){
while(x!=0)
{
x=0;
printf("%d", x);
}
}
return 0;
}
int main()
{
pthread_t thread1;
pthread_create(&thread1, NULL, changetoone, &x);
pthread_t thread2;
pthread_create(&thread2, NULL, changetozero, &x);
pthread_join(&thread1, NULL);
pthread_join(&thread2, NULL);
}
For some reason, the code is not running. I am not familiar with using pthread and I think I made some silly mistakes. Can anybody point out the mistake for me, please?
The first argument to pthread_join is pthread_t, not pthread_t*. So you shouldn't use & when calling it.
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
The actual behavior of the program is undefined because of lack of synchronization between the threads when accessing x. But this will at least allow the threads to run.
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;
}
I an learning pthread and I have a few questions.
Here is my code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define NUM_THREADS 10
using namespace std;
void *PrintHello(void *threadid)
{
int* tid;
tid = (int*)threadid;
for(int i = 0; i < 5; i++){
printf("Hello, World (thread %d)\n", *tid);
}
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
int t;
int* valPt[NUM_THREADS];
for(t=0; t < NUM_THREADS; t++){
printf("In main: creating thread %d\n", t);
valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
The code runs well and I don't call pthread_join. So I want to know, is pthread_join a must?
Another issue, is:
valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
equal to:
rc = pthread_create(&threads[t], NULL, PrintHello, &i);
It is not. But you need either pthread_exit() or pthread_join().
Here you called pthread_exit(), thats why the child threads continue execution even after the main thread terminates.
If there is any need for the main thread to wait till the child threads complete execution, you can use pthread_join().
I wanna write two threads, first will read a string from the console, and the second will output the number of characters in it.
To do so, I have to set the order of executing the threads, reading first, writing second.
Also I want one thread to execute at the time.
How can I do this?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *printCharacterNumber(void *ptr);
void *readMessage(void *ptr);
int main()
{
pthread_t thread1, thread2;
int iret1, iret2;
iret1 = pthread_create(&thread1, NULL, printMessage, NULL);
iret2 = pthread_create(&thread2, NULL, printCharacterNumber, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
void *readMessage(void *ptr)
{
char *message;
fscan("%s", &message);
}
void *printCharacterNumber(void *ptr)
{
printf("%s", message); // I'll add counting when it will work
}
The biggest interest of genine (pthread) threads is to enable parallel execution (taking profit of the several cores most laptops and desktops have)...
Read some pthread tutorial ...
You may want to use barriers. Read more about pthread_barrier_wait & pthread_barrier_init
If you want to serialize some counter, you could use (with recent C11 compilers, e.g. GCC 4.9) some atomic builtins, or more usually a mutex, see pthread_mutex_init & pthread_mutex_lock etc....:
static pthread_mutex_t mtx = PTHREAD_MUTEX_INIT;
static long counter;
void increment_serialized_counter (void) {
pthread_mutex_lock(&mtx);
counter++;
pthread_mutex_unclock(&mtx);
}
long get_serialized_counter (void) {
long r = 0;
pthread_mutex_lock(&mtx);
r = counter;
pthread_mutex_unclock(&mtx);
return r;
}
You probably should use a mutex for your message variable, if it was static!