我在啟動多個執行緒的程式中使用鎖(pthread_mutex_t),所有執行緒都接收到一個指向結構的指標,該結構包含指向該互斥鎖的指標。
所以有一個初始化的互斥體,所有結構都有一個指向它的指標,但它不能很好地作業,我不明白為什么?
這是一些示例代碼,我試圖使其盡可能小。
讓我們呼叫我的程式duck:
duck.c
# include "duck.h"
void *exec_threads(void *arg)
{
struct s_duck *duck;
duck = (struct s_duck*)arg;
pthread_mutex_lock(duck->mutex);
printf("duck nbr %i\n", duck->n);
pthread_mutex_unlock(duck->mutex);
return (NULL);
}
int main(void)
{
pthread_t *id;
pthread_mutex_t *mutex;
struct s_duck *duck;
int n;
int i;
n = 5; // number of threads
id = malloc(sizeof(int) * n); // allocate id[n]
mutex = malloc(sizeof(pthread_mutex_t)); // allocate mutex
pthread_mutex_init(mutex, NULL); // init mutex
duck = init_chain_ducks(mutex, n); // create chained list of structure
i = 0;
while (i < n)
{
pthread_create(&id[i], NULL, &exec_threads, duck); // launch threads
duck = duck->next;
i ;
}
i = 0;
while (i < n)
{
pthread_join(id[i], NULL); // join threads
i ;
}
write(1, "the end\n", 8);
return (0);
}
duck_chain.c
# include "duck.h"
struct s_duck *init_chain_ducks(pthread_mutex_t *mutex, int n)
{
struct s_duck *new;
struct s_duck *duck;
int i;
i = n;
duck = NULL;
while (i > 0)
{
new = malloc(sizeof(struct s_duck));
new->n = i;
new->mutex = mutex; // this is where the pointer to the mutex is stored
new->next = duck;
duck = new;
i--;
}
return (duck);
}
duck.h
#ifndef DUCK_H
# define DUCK_H
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <unistd.h>
# include <pthread.h>
struct s_duck
{
int n;
pthread_mutex_t *mutex;
struct s_duck *next;
};
struct s_duck *init_chain_ducks(pthread_mutex_t *mutex, int n);
#endif
如果我對互斥鎖使用全域變數,則效果很好。但是使用結構中的指標,我得到了類似未定義的行為:
大多數時候我得到這個輸出:
duck nbr 1
duck nbr 3
duck nbr 4
duck nbr 5
duck nbr 2
[2] 18914 segmentation fault (core dumped) ./a.out
段錯誤發生在期間,pthread_join()但我也經常遇到這兩個錯誤:
duck nbr 1
duck nbr 2
[wait indefinitely]
或者:
duck nbr 1
duck nbr 4
duck nbr 3
a.out: ../nptl/pthread_mutex_lock.c:81: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.
[2] 20394 abort (core dumped) ./a.out
我一定是在做一些基本的錯誤,但我不知道在哪里。
(編譯gcc duck.c duck_chain.c -lpthread:)
uj5u.com熱心網友回復:
pthread_t *id;
id = malloc(sizeof(int) * n); // allocate id[n]
id不是int- 它是pthread_t。應該是sizeof(pthread_t)。使用一個小技巧并使用指標指向。
id = malloc(sizeof(*id) * n);
編譯-g -Wall -Wextra -fsanitize=undefined,address- sanitizer 將幫助您發現此類錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416406.html
標籤:
