【发布时间】:2020-02-21 08:35:00
【问题描述】:
这是我在 StackOverflow 上的第一个问题。我正在尝试对 C 中的互斥体进行练习,要求我在矩阵 N x N 中找到一个元素。每个线程都必须检查每一行中的元素。当一个线程找到该元素时,它应该告诉其他人以便他们可以退出而无需继续搜索。我已经使用标志编写了一个解决方案来检查是否找到了元素,但无法弄清楚为什么行索引没有正确显示。我认为矩阵中的内存地址是连续的,所以我认为使用 % 操作数可以帮助我。我也不确定线程函数是否正确编写。你能帮我弄清楚为什么行索引没有正确显示吗?如果还有其他优雅的解决方案?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define MAXNTHREADS 1000000
#define MIN(a,b) (a < b ? a : b)
void * search (void *);
int nthreads;
char tosearch;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int flag;
int main (int argc, char **argv)
{
pthread_t * threads;
char * matrix;
if (argc != 3)
{
fprintf (stderr, "usage: matrix <char> <#threads>\n");
exit (-1);
}
nthreads = MIN (atoi(argv[2]), MAXNTHREADS);
tosearch = argv[1][0];
matrix = malloc (nthreads * nthreads);
threads = malloc (sizeof (pthread_t) * nthreads);
printf ("Insert %d elements\n", nthreads * nthreads);
for (int i = 0; i < nthreads; i ++)
{
for (int j = 0; j < nthreads; j ++)
{
scanf ("%c", matrix + i * nthreads + j);
getchar();
}
}
printf ("MATRIX:\n");
for (int i = 0; i < nthreads; i ++)
{
for (int j = 0; j < nthreads; j ++)
{
printf ("%c\t", *(matrix + i * nthreads + j));
}
printf ("\n");
}
for (int i = 0; i < nthreads; i ++)
{
pthread_create (threads + i, NULL, search, matrix + i * nthreads);
}
for (int i = 0; i < nthreads; i ++)
{
pthread_join (* (threads + i), NULL);
}
free (matrix);
free (threads);
exit (0);
}
void * search (void *arg)
{
printf ("Process %ld started\n", pthread_self());
for (int i = 0; i < nthreads; i ++)
{
pthread_mutex_lock (&mutex);
if (flag == 0)
{
if (*((char *)arg + i) == tosearch)
{
printf ("Element found by thread %ld in position %ld %d\n", pthread_self(), (((unsigned long)arg + nthreads) % nthreads), i);
flag = 1;
pthread_mutex_unlock (&mutex);
return NULL;
}
pthread_mutex_unlock (&mutex);
}
else
{
pthread_mutex_unlock (&mutex);
printf ("Process %ld exits\n", pthread_self());
pthread_exit (NULL);
}
}
printf ("Process %ld, found nothing\n", pthread_self());
pthread_exit (NULL);
}
【问题讨论】:
标签: c multithreading matrix operating-system mutex