Here is a program I wrote that uses 2 threads to operate on an array of 10 numbers.
- Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct Parameters {
int threadNum;
int *data;
int N;
int index;
int sum;
};
void *threadWork(void *param);
int main(void)
{
const int N = 10;
int array[N];
int i;
pthread_t t1, t2;
struct Parameters param1, param2;
for (i = 0; i < N; i++)
array[i] = i;
// create thread to process first half of data
param1.data = array;
param1.N = 5;
param1.index = 0;
param1.threadNum = 0;
pthread_create(&t1, NULL, threadWork, (void *)¶m1);
// create thread to process second half of data
param2.data = array;
param2.N = 5;
param2.index = 5;
param2.threadNum = 1;
pthread_create(&t2, NULL, threadWork, (void *)¶m2);
pthread_join(t1, NULL); // sleep the main() thread until thread 1 finishes
pthread_join(t2, NULL); // sleep the main() thread until thread 2 finishes
printf("The sum is %d from thread 0 and %d from thread 1\n", param1.sum, param2.sum);
for (i = 0; i < 10; i++)
printf("%d ", array[i]);
return (0);
}
void *threadWork(void *param)
{
struct Parameters *p;
int i;
p = (struct Parameters *)param;
printf("I am thread %d\n", p->threadNum);
p->sum = 0;
for (i = 0; i < p->N; i++) {
p->sum += p->data[i + p->index];
p->data[i + p->index] *= 2;
}
pthread_exit(NULL);
}
To compile, simply use:
- Code: Select all
gcc threadTest.c -lpthread -o threadTest
Expected results:
- Code: Select all
I am thread 0
I am thread 1
The sum is 10 from thread 0 and 35 from thread 1
0 2 4 6 8 10 12 14 16 18
Note that I haven't used any mutex's, which are used to lock up shared variables from being modified by other threads, since the data arrays operated on by both threads are mutually exclusive anyway.

