我有這樣的家庭作業的學校 - 我完成它發送,並得到0%:] ... 所以我想問一下,如果我的想法是正確的。例如,如果我想用線程編寫程序 - 我必須調用50次thrute,並有5個線程可用(我必須儘可能使用它們)。你能告訴我,如果我做錯了什麼 - 我想我是因爲printf說我只使用一個線程?我不太確定我會做這件事的方法。POSIX - 旗語,互斥線程Ç
在此先感謝 尼古拉JISA
這裏是我的源代碼:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define THREADS 5
#define CYCLES 50
sem_t sem1;
pthread_mutex_t m1, m2;
long int result = 0;
int thread_status[THREADS]; // status of threads, value -1 for working thread, other values for free threads
typedef struct Arg {
long int number;
int thread_ID; } ARG;
void * thrfunction (void * arg) {
int number = ((ARG *) arg)->number, thread_ID = ((ARG *) arg)->thread_ID, i;
thread_status[thread_ID] = -1;
pthread_mutex_unlock (& m1);
for (i = 0; i < number; i ++);
pthread_mutex_lock (& m2);
result = result + number;
printf ("Thread %d result = %ld\n", thread_ID, result);
pthread_mutex_unlock (& m2);
pthread_mutex_lock (& m1);
thread_status[thread_ID] = thread_ID;
sem_post (& sem1);
pthread_mutex_unlock (& m1);
return NULL; }
int main (int argc, char * argv[]) {
pthread_t thr[THREADS];
pthread_attr_t Attr; pthread_attr_init (& Attr); pthread_attr_setdetachstate (& Attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init (& m1, NULL); pthread_mutex_init (& m2, NULL);
sem_init (& sem1, 0, THREADS);
int i, j;
ARG * pom = (ARG *) malloc (sizeof (* pom));
for (i = 0; i < THREADS; i ++)
thread_status[i] = i;
for (i = 0; i < CYCLES; i ++) {
pom->number = rand() % 100000 * 10000;
sem_wait (& sem1);
pthread_mutex_lock (& m1);
for (j = 0 ; j == -1; j ++);
pthread_create (& thr[j], & Attr, thrfunction, (void *) pom); }
free (pom);
pthread_attr_destroy (& Attr); pthread_mutex_destroy (& m1); pthread_mutex_destroy (& m2); sem_destroy (& sem1);
for (i = 0; i < THREADS; i ++)
pthread_join (thr[i], NULL);
return 0;}
你相信下面的代碼? 「for(j = 0; j == -1; j ++); pthread_create(&thr [j],&Attr,thrfunction,(void *)pom);」 – Srikanth 2011-03-25 21:47:34
我也這麼認爲......但我對這個POSIX編程非常新鮮...... – 2011-03-25 22:07:40
好點Srikanth。尼古拉斯,你期望多少次(j = 0; j == -1; j ++);運行,你期望它做什麼?如果是時序循環,這是一個非常糟糕的主意。如果C編譯器選擇,則允許它完全移除該循環。 – 2011-03-25 22:44:50