Search
 
SCRIPT & CODE EXAMPLE
 

C

c multithreading sum from 0 to 1000

#include <stdio.h>
#include <pthread.h>
#include <stdint.h>

#define ARRAYSIZE 1000
#define THREADS 10

/* shared data */
int data[ARRAYSIZE]; /* Array of numbers to sum */
int sum = 0;
pthread_mutex_t mutex; /* mutually exclusive lock variable */
int wsize; /* size of work for each thread */
/* end of shared data */

void *slave(void *myid) {
int i,low,high,myresult=0;
low = (int)myid * wsize;

high = low + wsize;
for (i=low;i<high;i++)
myresult += data[i];
printf("I am thread:%d low=%d high=%d myresult=%d 
", (int)myid, low,high,myresult);

pthread_mutex_lock(&mutex);
sum += myresult; /* add partial sum to local sum */
pthread_mutex_unlock(&mutex);
}

void main() {
int i;
pthread_t tid[THREADS];
pthread_mutex_init(&mutex,NULL); /* initialize mutex */
wsize = ARRAYSIZE/THREADS; /* wsize must be an integer */
for (i=0;i<ARRAYSIZE;i++) /* initialize data[] */
data[i] = i+1;
for (i=0;i<THREADS;i++) /* create threads */
	if (pthread_create(&tid[i],NULL,slave,(void *)i) != 0)
		perror("Pthread_create fails");
for (i=0;i<THREADS;i++) /* join threads */
	if (pthread_join(tid[i],NULL) != 0)
		perror("Pthread_join fails");
printf("The sum from 1 to %i is %d
",ARRAYSIZE,sum);
}
Comment

PREVIOUS NEXT
Code Example
C :: anticonstitutionnellement 
C :: Calculate the area of a circle and modify the same program to calculate the volume of a cylinder given its radius and height. 
C :: Wait until an animation finishes - Selenium, Java 
C :: Manage Menu Driven Program using switch statement 
C :: float and double Output 
C :: FivemStore 
C :: Defining a macro in a header file 
C :: online c compiler with mpi 
C :: qgraphicsscene save all items to file 
C :: not repeated serial number in c 
C :: function pointer in c 
C :: perfect numbers in c 
C :: download file by command line windows 
C :: website how to solve c programming questions 
C :: unox reclame harmonica tabs 
Dart :: dart regex for email 
Dart :: flutter disbal PageView swipe 
Dart :: flutter rounded ElevatedButton 
Dart :: switch to another flutter channel eg. $ flutter channel beta $ flutter channel stable 
Dart :: scroll to top flutter 
Dart :: get file size flutter 
Dart :: flutter scroll to bottom 
Dart :: Floating Action Button rectangular shaped 
Dart :: text should come below if space not available row flutter 
Dart :: flutter image asset 
Dart :: get only time from datetime in dart 
Dart :: flutter padding between text and underline 
Dart :: retrieve shared preferences flutter map 
Dart :: convert future<list list in flutter 
Dart :: flutter random true false 
ADD CONTENT
Topic
Content
Source link
Name
5+6 =