//这是生产者Consumer程序的多线程代码,它运行//成功完成两个线程,但在线程加入之前只接收一个Segmentation错误,我真的无法搞清楚
#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);
}
}
答案 0 :(得分: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)