【发布时间】:2020-03-25 21:35:15
【问题描述】:
我正在尝试编写这样的代码:
输入 1:
2
123
abc
输出:
1a2b3c
第一行是下面的行数和我必须使用的线程数(最多 10 个)。 随机字符的行可能有不同的大小。
输入 2:
5
abcdef
123456789
xyz
ghi
j
输出 2:
a1xgjb2yhc3zid4e5f6789
我正在尝试使用互斥锁,但到目前为止我无法解决它。 任何帮助表示赞赏。
这是我的代码:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int n_strings;
char chars[10][100];
char output[1000];
pthread_t thread[10];
int count = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INICIALIZER;
void* mix_it_up(void* arg)
{
char* a = (char*) arg;
for (int i = 0; i < strlen(a); i++)
{
pthread_mutex_lock(&mutex);
output[count++] = a[i];
pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
scanf("%d", &n_strings);
for (int i = 0; i < n_strings; i++)
{
scanf("%s", chars[i]);
}
for (int i = 0; i < n_strings; i++)
{
pthread_create(&thread[i], NULL, mix_it_up, (void*) chars[i]);
}
for (int i = 0; i < n_strings; ++i)
{
pthread_join(thread[i], NULL);
}
pthread_mutex_destroy(&mutex);
printf("%s\n", output);
return(0);
}
感谢任何帮助。谢谢
【问题讨论】:
-
互斥锁只保证独占访问。它不保证线程将以任何特定顺序运行。
-
OT:为了便于阅读和理解:1) 请始终缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格。
-
你需要使用线程吗?使用嵌套的 for 循环不会容易得多。
-
OT:关于:
scanf("%s", chars[i]);和类似语句 1) 始终检查返回值(不是参数值)以确保操作成功。注意:这些函数返回成功的 '输入格式转换次数。在当前代码中,除 1 以外的任何返回值都表示发生了错误。 2) 当使用%s和/或%[...]时,总是包含比输入缓冲区长度小1 的MAX CHARACTERS 修饰符,因为这些说明符总是在输入中附加一个NUL 字节。这避免了缓冲区溢出和由此产生的未定义行为
标签: c multithreading pthreads