- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我编写了一个程序,其中主线程创建了 2 个子线程。等待一段随机时间,然后生成一个介于 1 和 6 之间的随机值,并将该值放入 randomValue 变量中。另一个等待并读取全局变量 randomValue 并打印变量。所以我使用单个信号量来确保读取的线程将始终读取另一个线程写入的值。
我想修改让每个线程都不知道 x loops( 2,3...) 以便它可以产生 x 倍的随机值并将这个值放入 randomValue 并且另一个线程将读取x 倍于 randomValue 变量并将打印它。欢迎任何修改代码的想法。非常感谢。
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
/* variable shared by producer and consumer
(producer writes a value between 1 and 6) */
long randomValue = 0;
/**semaphore **/
sem_t mex;
// function that create a random sleep-time (to induce unpredictability)
static int duration(int min, int max)
{
static int first_time = 1;
// Seed the random number generator with the current time
// of day if we haven't done so yet.
if (first_time) {
first_time = 0;
srand48((int) time(NULL));
}
return (int) (min + drand48()*(max - min));
}
/* producer program */
void *producer(void *arg) {
char statearray[256];
// Initialize random generator
// Note that initstate and random are not threadsafe
initstate(time(NULL), statearray, 256);
sleep(duration(1,3));
printf("prod: producing ...\n");
//random value 1 et 6
randomValue = random();
randomValue = ((double) randomValue / RAND_MAX)*6+1;
//put the value
printf("prod: delivering %ld\n", randomValue);
sem_post(&mex);
pthread_exit(NULL);
}
/* consumer program */
void *consumer(void *arg) {
sleep(duration(1,5));
sem_wait(&mex);
printf("cons: consuming ...\n");
//
printf("cons: received %ld\n", randomValue);
pthread_exit(NULL);
}
/* main thread */
int main(int argc, char *argv[]) {
pthread_t tidprod, tidcons;
if (sem_init(&mex,0,0) != 0){
perror("sem_init");
exit(EXIT_FAILURE);
}
if (pthread_create(&tidprod, NULL, producer, NULL) != 0) {
perror("pthread_create");
}
if (pthread_create(&tidcons, NULL, consumer, NULL) != 0) {
perror("pthread_create");
}
if (pthread_join(tidcons, NULL) != 0) {
perror("pthread_join prod");
}
if (pthread_join(tidprod, NULL) != 0) {
perror("pthread_join prod");
}
fflush(stdout);
pthread_exit(EXIT_SUCCESS);
}
最佳答案
你可以做一些你想做的事:
因此,您可以这样更改代码:
信号量声明
/*semaphores */
/* Set by producer when production is ready */
sem_t mex_prod;
/* Set by consumer when ready to consume */
sem_t mex_cons;
信号量初始化
/* by default, nothing produced */
if (sem_init(&mex_prod,0,0) != 0){
perror("sem_init");
exit(EXIT_FAILURE);
}
/* by default, consumer is not ready */
if (sem_init(&mex_cons,0,0) != 0){
perror("sem_init");
exit(EXIT_FAILURE);
}
生产者线程函数
(我删除了你的评论)
void *producer(void *arg) {
char statearray[256];
initstate(time(NULL), statearray, 256);
/* choose how much to product */
int number_of_productions = 2 + random()%5;
printf("prod: %d to produce\n", number_of_productions );
/* this loop can be replaced by some for (i = 0; i< num; ++i) loop */
while(number_of_productions--)
{
sleep(duration(1,3));
/* wait for consumer to be ready */
sem_wait(&mex_cons);
printf("prod: producing ...\n");
randomValue = random();
randomValue = ((double) randomValue / RAND_MAX)*6+1;
printf("prod: delivering %ld\n", randomValue);
sem_post(&mex_prod);
}
sem_wait(&mex_cons);
/* generate a special value to tell the consumer that no new value
will be given */
randomValue = -1;
sem_post(&mex_prod);
pthread_exit(NULL);
}
消费者线程函数
void *consumer(void *arg) {
/* tell producer that consumer is ready */
sem_post(&mex_cons);
/* since we don't know how many value will be generated, we have an
infinite loop */
while(1)
{
sleep(duration(1,5));
sem_wait(&mex_prod);
printf("cons: consuming ...\n");
printf("cons: received %ld\n", randomValue);
/* value has been consumed, tell producer we are ready for a new one */
sem_post(&mex_cons);
/* if randomValue is -1, we break the loop since no more value will come */
if (-1 == randomValue)
break;
}
pthread_exit(NULL);
}
关于c - Thread main with 2 sons thread循环x次产品和消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635670/
完成此任务的最佳方法是什么:主线程(线程 A)创建另外两个线程(线程 B 和线程 C)。线程 B 和 C 执行繁重的磁盘 I/O,最终需要将它们创建的资源传递给线程 A,然后调用外部 DLL 文件中的
我是一名对 Julia 语言感兴趣的新手程序员。文档( https://docs.julialang.org/en/v1/base/multi-threading/ )说 Threads.@threa
python中的thread.start_new_thread和threading.Thread.start有什么区别? 我注意到,当调用 start_new_thread 时,新线程会在调用线程终止
我正在学习安卓蓝牙编程。我从 Google 的 Android 开发者网站上复制了大部分代码以供学习。这个想法是监听服务器上的连接是在一个新线程中完成的,而不会阻塞 UI 线程。当收到连接请求时,连接
执行对象方法的线程是否依赖于创建它的线程上的线程? 假设您的 java 应用程序中有两个线程 Thread1 和 Thread2,以及两个类 ClassA 和 ClassB。 您在 Thread1 上
我正在用这段代码测试 C++11 线程,但是在创建线程时,我遇到了错误没有匹配函数调用 'std::thread::thread()'. 这就像我给 std::thread ctr 的函数有什么问题,
我有如下类 eventEngine 和网关: class eventEngine { public: eventEngine(); std::thread threa; std
我需要运行与列表 dirlist 中的元素一样多的 Observer 类线程。当我运行它 python 控制台时,它可以正常工作。 class Observer(Thread): def ru
我在一本 Java 书中读到了下面的代码。我知道主类默认继承 Thread 类,所以 currentThread();而不是 Thread.currentThread();也会做这项工作。 但我不明白
我在我的系统中使用第 3 方 API,该 API 启动一个永久运行的用户线程。一旦我的程序结束,JVM 由于该线程而继续运行,因此我尝试获取此线程引用并通过更改它 thread.setDaemon(t
我所知道的 Python 中的每个对象都可以通过调用来处理其基类初始化: super(BaseClass, self).__init__() threading.Thread 的子类似乎不是这种情况,
在我最近从事的 Xamarin 项目中,我可以看到开发人员使用了 Java.Lang.Thread 以及 System.Threading.Thread(用于非常相似的操作 - 例如在后台加载数据)。
我在 Julia 中运行双循环。代码非常简单。 w = rand(1000,1000) function regular_demo(w::Array{Float64, 2}) n = size
我在 Windows 上使用 Python 3。我正在使用 threading.Thread动态运行一个函数,我可以带参数或不带参数调用它。我正在设置一个列表,其中的第一项是定义路径的字符串。其他参数
我遇到了一些使用线程模块(使用 Python 2.6)管理线程的示例。 我想了解的是这个例子是如何调用“运行”方法的,在哪里调用的。我在任何地方都看不到它。 ThreadUrl 类在 main() 函
假设我从 threading.Thread 派生: from threading import Thread class Worker(Thread): def start(self):
关闭。这个问题需要debugging details .它目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and th
使用 WinDbg 和 SOS,我有以下内容: 0:011> !threads ThreadCount: 7 UnstartedThread: 0 BackgroundThread: 4 Pendin
App Engine 给出错误: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfe
我正在尝试将 Swing JEditorPane 嵌入到 JavaFX 项目中,如下代码所示。 Platform.runLater(() -> { SyntaxTester ob = new
我是一名优秀的程序员,十分优秀!