我试图在每个线程上创建一个运行200个线程并增加1000次的程序,因此最终结果必须是200000 这时使用互斥锁
我编译没有警告的代码,但是当我运行程序时,它给了我这个错误:错误 - pthread_mutex_lock()失败:参数无效
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <pthread.h>
#include "debug.h"
#include "memory.h"
#define NUM_THREADS 200
#define C_ERRO_PTHREAD_CREATE 1
#define C_ERRO_PTHREAD_JOIN 2
#define C_ERRO_MUTEX_INIT 3
#define C_ERRO_MUTEX_DESTROY 4
#define C_ERRO_MUTEX 5
void *task(void *arg);
typedef struct
{
int contador;
pthread_mutex_t mutex;
}thread_params_t;
int main(int argc, char *argv[])
{
pthread_t tids[NUM_THREADS];
thread_params_t thread_params;
/* Disable warnings */
(void)argc; (void)argv;
/* Mutex */
if ((errno = pthread_mutex_init(&thread_params.mutex, NULL)) != 0)
ERROR(C_ERRO_MUTEX_INIT, "pthread_mutex_init() failed!");
/* Contador */
thread_params.contador = 0;
// Criação das threads + passagem de parametro
for (int i = 0; i < NUM_THREADS; i++){
if ((errno = pthread_create(&tids[i], NULL, task, &thread_params)) != 0)
ERROR(10, "Erro no pthread_create()!");
}
// Espera que todas as threads terminem
for (int i = 0; i < NUM_THREADS; i++){
if ((errno = pthread_join(tids[i], NULL)) != 0)
ERROR(11, "Erro no pthread_join()!\n");
}
/* Mostra valor do campo contador */
printf("Contador = %d\n", thread_params.contador);
/* Destroi o mutex */
if ((errno = pthread_mutex_destroy(&thread_params.mutex)) != 0)
ERROR(C_ERRO_MUTEX_DESTROY, "pthread_mutex_destroy() failed!");
return 0;
}
// Thread
void *task(void *arg)
{
pthread_mutex_t mutex;
// cast para o tipo de dados enviado pela 'main thread'
thread_params_t *params = (thread_params_t *) arg;
usleep(100*(random() % 2)); /* Adormece entre 0 a 100 usecs */
//inicio secção critica
if ( (errno = pthread_mutex_lock(&mutex)) != 0)
ERROR(C_ERRO_MUTEX, "pthread_mutex_lock() failed");
int cont = params->contador;
sched_yield();
usleep(100*(random() % 2)); /* Adormece entre 0 a 100 usecs */
params->contador = cont + 1000 ;
//fim secção critica
if ( (errno = pthread_mutex_unlock(&mutex)) != 0)
ERROR(C_ERRO_MUTEX, "pthread_mutex_unlock() failed");
return NULL;
}
答案 0 :(得分:0)
已经找到了答案,在线程中我需要制作指针,params-&gt; mutex因为我的结构,因此我不需要再次声明互斥锁
composer show package/name