【发布时间】:2011-03-25 21:19:36
【问题描述】:
我有这个作业要上学 - 我完成了它并发送它并得到 0% :] ... 所以我想问问我的想法是否正确。例如,如果我想用线程编写程序 - 我必须调用 50 次 thrfunction 并且我有 5 个线程可用(并且我必须尽可能多地使用它们)。如果我做错了什么,请告诉我 - 我想我是因为 printf 说我只使用一个线程?我不太确定我会做这件事的方法。
提前致谢 尼古拉斯·吉萨
这是我的源代码:
#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 );"
-
是的,我想是的......但我对这个 POSIX 编程非常陌生......
-
好点 Srikanth。尼古拉斯,你期望多少次 (j = 0 ; j == -1; j ++ );运行,你期望它做什么?如果它是一个时序循环,这是一个非常糟糕的主意。如果 C 编译器愿意,它可以完全删除该循环。
-
或者,如果您在 64 位系统上编译,您的程序可能永远无法完成。
-
I 除了之后 ( j = 0 ; j == -1; j ++ ); “j”将是第一个空闲线程的标识符