【问题标题】:Segmentation Fault on multithreaded Producer Consumer C Program多线程生产者消费者 C 程序的分段错误
【发布时间】:2014-07-15 19:33:05
【问题描述】:

//这是生产者消费者程序的多线程代码,它运行//两个线程都成功完成,但在线程加入之前收到一个分段错误,我真的无法弄清楚

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

void* writer_function ();
void* reader_function ();
char buffer[9];

sem_t empty_buffers;
sem_t full_buffers;

int main()
{
 pthread_t thread1, thread2;
 //const char *message1 = "Thread 1";
 //const char *message2 = "Thread 2";
 int  iret1, iret2;

 sem_init(&empty_buffers,0,8);
 sem_init(&full_buffers,0,0);

/* Create independent threads each of which will execute function */

 iret1 = pthread_create( &thread1, NULL,writer_function, NULL);
 if(iret1)
 {
     fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
     exit(EXIT_FAILURE);
 }

 iret2 = pthread_create( &thread2, NULL, reader_function(), NULL);
 if(iret2)
 {
     fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
     exit(EXIT_FAILURE);
 }

 // Runs Successfully ,and segmentation fault here  
 pthread_join( thread1, NULL);
 pthread_join( thread2, NULL);

 printf("pthread_create() for thread 1 returns: %d\n",iret1);
 printf("pthread_create() for thread 2 returns: %d\n",iret2);

 sem_destroy(&empty_buffers);
 sem_destroy(&full_buffers);

 /* Wait till threads are complete before main continues. Unless we  */
 /* wait we run the risk of executing an exit which will terminate   */
 /* the process and all threads before the threads have completed.   */


 printf("This marks the end and the threads to be joined \n ");
 //exit(EXIT_SUCCESS);
 return 0;

}

void* writer_function ()
{
     int i ;
     for (i = 0 ; i < 40 ; i++){
        char c = (i + 66);
        sem_wait(&empty_buffers);
        buffer[i%8] = c;
        sem_post(&full_buffers);
        printf("  WRITER:the letter Written is %c\n", c);
     }
}

void* reader_function ()
{
     int i ;
     for (i = 0 ; i < 40 ; i++){
        sem_wait(&full_buffers);
        char c = buffer[i%8];
        sem_post(&empty_buffers);
        printf("READER:the letter Received is %c\n", c);
     }
}

【问题讨论】:

    标签: c multithreading semaphore segmentation-fault


    【解决方案1】:

    改变:

    iret2 = pthread_create( &thread2, NULL, reader_function(), NULL);
    

    iret2 = pthread_create( &thread2, NULL, reader_function, NULL);
    

    添加返回NULL;对于两个函数 reader_function, writer_function 在循环后将它们的标题从 writer_/reader_function() 更改为 writer_/reader_function(void *args)

    【讨论】:

      猜你喜欢
      • 2014-12-02
      • 2021-07-26
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2018-09-24
      • 2017-03-10
      • 2017-02-01
      • 1970-01-01
      相关资源
      最近更新 更多