提问人:JaChceTylkoZdacStudia 提问时间:11/13/2023 更新时间:11/13/2023 访问量:35
如何从线程接收信息到主线程,然后将信息返回 / C 语言、pthreads、互斥锁
How to receive information from thread to main thread and then give information back / C language, pthreads, mutex
问:
- 线程数应由 #define NUM_THREADS 编号指定
- 使用互斥锁或信号量的程序版本
编写一个程序,其中每个线程生成两个随机数。 然后主线程 ( int main() ) 计算各个线程生成的总和,并将信息传递给线程,以了解给定线程是赢了还是输了。最后,每个线程都会打印我赢了或输了的消息。
你能帮我如何正确地编写该任务吗?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define num_threads 5
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // Initialization and declaration of mutex
void* thread_function(void* arg) {
int id = *(int*)arg;
int number1 = rand() % 100;
int number2 = rand() % 100;
pthread_mutex_lock(&lock); // Lock the mutex
// Your thread logic goes here
pthread_mutex_unlock(&lock); // Unlock the mutex
}
int main() {
srand(time(NULL));
pthread_t threads[num_threads];
int thread_ids[num_threads];
// Creating threads
for (int i = 0; i < num_threads; ++i) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_function, (void*)&thread_ids[i]);
}
// Checking the sums generated by the threads
// Waiting for the threads to finish
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
答: 暂无答案
评论
// Initialization and declaration of mutex
i++; // increment i
rand
rand_r