Yeni bir process yaratıp onu kontrol etmeye çalışmak (fork v.b.) çok fazla sistem mesarifi yaptığından, bu threadleri kullanıyoz efem. Bunlar çok daha hesaplı bir alana bir de bedava g,b, diyim öyle beleş bişe yani. Kullanımı da basit ... ahanda 5 -6 fonksiyon o kadar...
Bunalr nerede kullanılır, paralel programlama nedir v.s. filan diye uzun uzun anlatmayacağım direk olaya dalıyorum.
Fonksiyonlar
____________
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg)
: yürütülebilir yeni bir thread yaratır
thread : yeni thread pointer'ı
attr : thread özellikleri (default'u NULL dur)
start_routine : threadin yürütüleceği fonksiyonun pointer'ı
arg : fonksiyona paslanabilecek argümanlar. (yoksa NULL yazılabilir)
void pthread_exit(void *value_ptr);
: thread den çıkmaya yarar
int pthread_attr_destroy(pthread_attr_t *attr);
: attribute obje lerini yok eder.
int pthread_attr_init(pthread_attr_t *attr);
: attribute objelerini tanıtır
Örnek Kod
Bunalr nerede kullanılır, paralel programlama nedir v.s. filan diye uzun uzun anlatmayacağım direk olaya dalıyorum.
Fonksiyonlar
____________
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg)
: yürütülebilir yeni bir thread yaratır
thread : yeni thread pointer'ı
attr : thread özellikleri (default'u NULL dur)
start_routine : threadin yürütüleceği fonksiyonun pointer'ı
arg : fonksiyona paslanabilecek argümanlar. (yoksa NULL yazılabilir)
void pthread_exit(void *value_ptr);
: thread den çıkmaya yarar
int pthread_attr_destroy(pthread_attr_t *attr);
: attribute obje lerini yok eder.
int pthread_attr_init(pthread_attr_t *attr);
: attribute objelerini tanıtır
Örnek Kod
#include
#include
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
int tid;
tid = (int)threadid;
printf("Hello World! It's me, thread #%d!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc, t;
for(t=0; tVe bu örneğin çıktısı şöyle olur :
In main: creating thread 0
In main: creating thread 1
Hello World! It's me, thread #0!
In main: creating thread 2
Hello World! It's me, thread #1!
Hello World! It's me, thread #2!
In main: creating thread 3
In main: creating thread 4
Hello World! It's me, thread #3!
Hello World! It's me, thread #4!
Join işlemleri
int pthread_join(pthread_t thread, void **value_ptr);
: bulunduğu thread in yütülmesini, çağrılan thread'in işi bitene kadar, durdurur.
Örnek Kod
#include
#include
#define NUM_THREADS 3
void *BusyWork(void *null)
{
int i;
double result=0.0;
for (i=0; i<1000000; i++) { result = result + (double)random(); } printf("result = %e\n",result); pthread_exit((void *) 0); } int main (int argc, char *argv[]) { pthread_t thread[NUM_THREADS]; pthread_attr_t attr; int rc, t; void *status; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t=0; t
pthread_t pthread_self(void);
: Thread ID ti döner
int pthread_equal(pthread_t t1, pthread_t t2);
: iki threadin ID lerini karşılaştırır
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
: Mutex'i belirtilen özelliklerde yeni bir mutex yaratır.
(PTHREAD_MUTEX_INITIALIZER static değişkenine atamayla da mutex initialize edilebilr.)
int pthread_mutex_destroy(pthread_mutex_t *mutex);
: mutexi free ler ve yok eder.
int pthread_mutex_lock(pthread_mutex_t *mutex);
: Mutexi kilitler
int pthread_mutex_unlock(pthread_mutex_t *mutex);
: Mutex kilitlenmişse kilidi kaldırır, aksi takdirde hata döner.
int pthread_mutex_trylock(pthread_mutex_t *mutex);
: Mutexi kilitlemeye çalışır ama zaten kilitlenmişse, hemen error döner.
Örnek Kod
#include
#include
#include
/*
The following structure contains the necessary information
to allow the function "dotprod" to access its input data and
place its output into the structure.
*/
typedef struct
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
/* Define globally accessible variables and a mutex */
#define NUMTHRDS 4
#define VECLEN 100
DOTDATA dotstr;
pthread_t callThd[NUMTHRDS];
pthread_mutex_t mutexsum;
/*
The function dotprod is activated when the thread is created.
All input to this routine is obtained from a structure
of type DOTDATA and all output from this function is written into
this structure. The benefit of this approach is apparent for the
multi-threaded program: when a thread is created we pass a single
argument to the activated function - typically this argument
is a thread number. All the other information required by the
function is accessed from the globally accessible structure.
*/
void *dotprod(void *arg)
{
/* Define and use local variables for convenience */
int i, start, end, offset, len ;
double mysum, *x, *y;
offset = (int)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
/*
Perform the dot product and assign result
to the appropriate variable in the structure.
*/
mysum = 0;
for (i=start; iCondition Variables
Threadler arası senkronizasyonu sağlamanın baaşka bir yolu da Condition Variables tır. Mutexler threadlerin veriye erişmelerini kontrol ederek bu senkronizasyonu sağlarlarken Conditional Variables verinin gerçek değerini (eğer bekleniyorsa) paslayarak senkronizasyon sağlarlar.
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
: Cond Var. initialize eder. (pthread_cond_t cond = PTHREAD_COND_INITIALIZER; şeklinde de gerçekleşebilir.)
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_condattr_init (attr)
int pthread_condattr_destroy(pthread_condattr_t *attr);
int pthread_cond_wait(pthread_cond_t *restrict cond, thread_mutex_t *restrict mutex);
: beklenen koşul gerçekleşene kadar çağırıldığı thread i kilitler.
int pthread_cond_signal(pthread_cond_t *cond);
: koşulu bekleyen threadi harekete gçirmek için çağırıldığı threadden sinyal yollar. Eğer birden çok thread bu Cond. Var. bekliyor ise bu fonksiyon yerine pthread_cond_broadcast kullanılır.
Örnek Kod :
#include
#include
#define NUM_THREADS 3
#define TCOUNT 10
#define COUNT_LIMIT 12
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *idp)
{
int j,i;
double result=0.0;
int *my_id = idp;
for (i=0; ipthread_mutex_lock(&count_mutex);
count++;
/*
Check the value of count and signal waiting thread when condition is
reached. Note that this occurs while mutex is locked.
*/
if (count == COUNT_LIMIT) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %d, count = %d Threshold reached.\n",
*my_id, count);
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\n",
*my_id, count);
pthread_mutex_unlock(&count_mutex);
/* Do some work so threads can alternate on mutex lock */
for (j=0; j<1000; j++)
result = result + (double)random();
}
pthread_exit(NULL);
}
void *watch_count(void *idp)
{
int *my_id = idp;
printf("Starting watch_count(): thread %d\n", *my_id);
/*
Lock mutex and wait for signal. Note that the pthread_cond_wait
routine will automatically and atomically unlock mutex while it waits.
Also, note that if COUNT_LIMIT is reached before this routine is run by
the waiting thread, the loop will be skipped to prevent pthread_cond_wait
from never returning.
*/
pthread_mutex_lock(&count_mutex);
if (countpthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %d Condition signal
received.\n", *my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
int i, rc;
pthread_t threads[3];
pthread_attr_t attr;
/* Initialize mutex and condition variable objects */
pthread_mutex_init(&count_mutex, NULL);
pthread_cond_init (&count_threshold_cv, NULL);
/* For portability, explicitly create threads in a joinable state */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]);
pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]);
pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]);
/* Wait for all threads to complete */
for (i=0; ipthread_join(threads[i], NULL);
}
printf ("Main(): Waited on %d threads. Done.\n", NUM_THREADS);
/* Clean up and exit */
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(NULL);
}
Eh bu kadar yeterli daha detaylı bilgi için kaynak : https://computing.llnl.gov/tutorials/pthreads/#Abstract
Hiç yorum yok:
Yorum Gönder