Pages

Sunday, February 19, 2012

C ile Multithreading Örneği

Geçen dönem İşletim Sistemleri dersinin en heyecanlı lab dersi Thread konusundakiydi. Bir programın yapacağı işi parçalara bölmek ve her parçayı ayrı ayrı thread’lere paralel olarak yaptırma fikri gerçekten herkesin ilgisini çekmişti.

Labda yaptığımız örnek ise Silberschatz’ın kitabındaki matris çarpma projesi oldu. Labdan kısaca bahsedeyim: A ve B matrisini çarpıp C matrisi elde ediyoruz. Yalnız bu çarpma işlemini yaparken C’nin her bir elemanını ayrı ayrı thread’lerde hesaplıyoruz. Örneğin, A 3x2 bir matris ve B 2x3 bir matris olsun, çarpma sonucu oluşan C matrisi bu durumda 3x3 olur ve C matrisini oluşturmak için toplam 9 thread kullanılırız. Umarım anlatabilmişimdir.

Labın kodlama kısmı şöyle:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define M 3
#define K 2
#define N 3
#define NUM_THREADS M * N
/* Global variables for threads to share */
int A[M][K] = {{1, 4}, {2, 5}, {3, 6}};
int B[K][N] = {{8, 7, 6}, {5, 4, 3}};
int C[M][N];
/* Structure for passing data to threads */
struct v
{
int i; /* row */
int j; /* column */
};
void *runner(void *ptr); /* the thread */
int main(int argc, char **argv)
{
int i, j;
int thread_counter = 0;
pthread_t workers[NUM_THREADS];
/* We have to create M * N worker threads */
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
struct v *data = (struct v *) malloc(sizeof(struct v));
data->i = i;
data->j = j;
/* Now we will create the thread passing it data as a paramater*/
pthread_create(&workers[thread_counter], NULL, runner, data);
pthread_join(workers[thread_counter], NULL);
thread_counter++;
}
}
/* Waiting for threads to complete */
for (i = 0; i < NUM_THREADS; i++)
{
pthread_join(workers[i], NULL);
}
for(i = 0; i < M; i++)
{
for(j = 0; j < N; j++)
{
printf("%d\t", C[i][j]);
}
printf("\n");
}
return 0;
}
void *runner(void *ptr)
{
/* Casting paramater to struct v pointer */
struct v *data = ptr;
int i, sum = 0;
for(i = 0; i < K; i++)
{
sum += A[data->i][i] * B[i][data->j];
}
C[data->i][data->j] = sum;
pthread_exit(0);
}
view raw thread_project2 hosted with ❤ by GitHub

Şimdi ise nasıl derleyip çalıştırdığımıza ve çıktısına bakalım.

ozan@pardus2011 Labs $ gcc thread_project2.c -o thread_project2.o -pthread
ozan@pardus2011 Labs $ ./thread_project2.o  
28      23      18
41      34      27
54      45      36

Görüşmek üzere.

No comments:

Post a Comment