2013-02-13 45 views
0

我写了以下短的应用程序来解决障碍问题。 此应用程序应该保证三个相同的线程运行相同的线程方法,都将在通用代码部分“相遇”。 我跑它,它似乎确定。 我的问题是:屏障为N线程与semphore

1)它是正确的吗?

2)有N个线程实现它的首选和有效的方法吗?

这里是代码:

static sem_t t_1_sem; 

static sem_t t_2_sem; 

static sem_t t_3_sem; 



struct my_thread_info { 
    int num; 
}; 

void *thread(void *vargp) 

{ 

     struct my_thread_info *info = (struct my_thread_info*)vargp; 
     static int counter=0; 
     counter++; 

     if (info->num == 1) { 
       printf("info->num=%d\n", info->num); 
       if (counter<3) 
        sem_wait(&t_1_sem); // down 
       else { 
        sem_post(&t_2_sem); // up 
        sem_post(&t_3_sem); // up     
       } 

     } else 
      if (info->num == 2) { 
       printf("info->num=%d\n", info->num); 
      if (counter<3)    
        sem_wait(&t_2_sem);    
       else { 
        printf("info->num=%d\n", info->num); 
        sem_post(&t_1_sem); 
        sem_post(&t_3_sem); //up    
      } 
      } 
      else 
      if (info->num == 3) { 
       printf("info->num=%d\n", info->num); 
      if (counter<3)    
        sem_wait(&t_3_sem);    
       else { 
        sem_post(&t_1_sem); 
        sem_post(&t_2_sem); //up    
      } 
     } 
     printf("meeting occured!\n"); 

} 

int main() 
{ 
    pthread_t tid0, tid1, tid2; 

    struct my_thread_info info1, info2, info3; 
    info1.num = 1; 

    sem_init(&t_1_sem, 0, 0); 
    sem_init(&t_2_sem, 0, 0); 
    sem_init(&t_3_sem, 0, 0); 

    pthread_create(&tid0, NULL, thread, &info1); 
    info2.num = 2; 

    pthread_create(&tid1, NULL, thread, &info2); 

    info3.num = 3; 
    pthread_create(&tid2, NULL, thread, &info3); 


    pthread_join(tid0, NULL); 
    pthread_join(tid1, NULL); 
    pthread_join(tid2, NULL); 
    pause(); 
    return 0; 

} 

问候 凯文

+0

又见pthread_barrier_XXX功能,如果你只需要障碍。 – nos 2013-02-13 16:07:33

回答

0

首先所有counter变量是无人防守 - 做counter++当u有可能的竞争条件。使用互斥锁;

至于做N个线程 - 使用线程/信号量的数组是国际海事组织可以接受的,我有代码利用该设计,它运作良好。

0

1.不是不正确。像counter++;这样的增量会导致竞争条件,并且它不会正确增加计数器。你会想要在关键部分包围它。

2.

static pthread_mutex_t cs_mutex = PTHREAD_MUTEX_INITIALIZER; 
static sem_t t_sem; 

void *thread(void *vargp) 
{ 
    static int counter=0; 
    pthread_mutex_lock(&cs_mutex); 
    counter++; 
    pthread_mutex_unlock(&cs_mutex); 

    if(counter == NO_THREADS) 
     sem_post(&t_sem); 

    sem_wait(&t_sem); 
    sem_post(&t_sem); 
} 
int main(int argc, char *argv[]){ 

    pthread_t tids[NO_THREADS]; 
    sem_init(&t_sem, 0, 0); 

    for(i=0; i<NO_THREADS; i++){ 
     pthread_create(&tids[i], NULL, thread, NULL); 
    } 

    for(i=0; i<NO_THREADS; i++){ 
     pthread_join(&tids[i], NULL); 
    } 
    pause(); 
    return 0; 
} 
+0

不是你的'计数器'访问条件不安全?无论如何,你的答案与我的不同? :P – Dariusz 2013-02-13 16:03:41

+0

我认为OP需要更具体的东西......? 'if(counter == NO_THREADS)'很好,因为我们不关心信号量的正值。 – JosephH 2013-02-13 16:07:31

+0

if的情况可能永远不会实现... – Dariusz 2013-02-13 16:10:34