簡體   English   中英

分段錯誤使用信號量同步 C 中的 3 個線程

[英]Segmentation fault usint semaphores to synchronize 3 threads in C

我正在使用信號量來同步 c 中的 3 個線程,以便打印像aabcaabcaabc這樣的序列,但我的代碼在 Linux 中給出了分段錯誤。

我看不出我的代碼有什么問題,我制作了 3 個信號量,每個線程一個,並以線程 1 打印aa和線程 2 打印b的方式同步它們,依此類推。

我該怎么做才能讓它發揮作用?

#include<pthread.h>
#include<semaphore.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
sem_t* sem1;
sem_t* sem2;
sem_t* sem3;


void* printA(void* a)
{
    sem_wait(sem2);
    printf("a");
    printf("a");
    sem_post(sem2);
}

void* printB(void* a)
{
    sem_wait(sem2);
    printf("b");
    sem_post(sem3);
}

void* printC(void* a)
{

    sem_wait(sem3);
    printf("c");
    sem_post(sem1);

}

int main()
{

  sem_init(sem1, 0, 1);
  sem_init(sem2, 0, 0);
  sem_init(sem3, 0, 0);

  pthread_t thread1;
  pthread_t thread2;
  pthread_t thread3;

  pthread_create(&thread1, NULL, &printA, NULL);
  pthread_create(&thread2, NULL, &printB, NULL);
  pthread_create(&thread3, NULL, &printC, NULL);

  pthread_join(thread1, NULL);
  pthread_join(thread2, NULL);
  pthread_join(thread3, NULL);

  sem_destroy(sem1);
  sem_destroy(sem2);
  sem_destroy(sem3);
}

調試器中運行您的代碼會顯示 seg-fault 的位置。 使用回溯第 41 行或 main.c ( sem_init(sem1, 0, 1); )。

Reading symbols from a.out...done.
(gdb) run
Starting program: /home/a.out 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, main () at main.c:41
41        sem_init(sem1, 0, 1);
(gdb) next

Program received signal SIGSEGV, Segmentation fault.
__new_sem_init (sem=0x0, pshared=0, value=1) at sem_init.c:44
44      sem_init.c: No such file or directory.
(gdb) bt
#0  __new_sem_init (sem=0x0, pshared=0, value=1) at sem_init.c:44
#1  0x00000000004008a6 in main () at main.c:41

問題是sem1是一個初始化的指針。 您需要將指針傳遞給實例化的sem_t object。

sem_t sem1;
sem_t sem2;
sem_t sem3;

然后:

  sem_init( &sem1, 0, 1);
  sem_init( &sem2, 0, 0);
  sem_init( &sem3, 0, 0);

當然,在其他地方將sem1更改為&sem1等。

請注意,雖然這會阻止您的代碼出現段錯誤,但它會掛起,因為兩個線程都沒有等待sem1 可能printA()應該等待sem1而不是sem2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM