我怎样才能使用线程? [英] How can I use threads?

查看:110
本文介绍了我怎样才能使用线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写程序

一个函数得到数字

另一个计算平均数的函数

它应该并行完成并使用线程



我尝试过:



i want to write program
that one function get numbers
another function counting avg of numbers
it should be done parallel and used threads

What I have tried:

i want to write program 
that one function get numbers
another function counting avg of numbers
it should be done parallel and used threads

推荐答案

这不是一个好用的线程:一个是等待用户输入然后几乎没有死。另一个等待最适合做某事,然后几乎没有死。

它几乎肯定效率低,甚至尝试通过单独的线程执行此操作比执行此操作更慢单线程!



找到一个更好的并行化任务示例,并查看 BackgroundWorker Class(System.ComponentModel) [ ^ ]有关如何入门的示例。这是一个非常简单的介绍。
That isn't a good use of threads: one is waiting for the user to type then dies almost nothing. The other waits for the fittest to do something, and then dies almost nothing as well.
It's almost certainly less efficient and slower to even try to do this via separate threads than it is to do it in a single thread!

Find a better example of a task to "parallelize", and look at the BackgroundWorker Class (System.ComponentModel)[^] for an example of how to get started. It's a pretty simple introduction.


网上有很多文章。只需按照其中一个。如果你在尝试的时候看到任何问题,请写一些代码

。发布你的问题。



请参考使用C#进行多线程处理 [ ^ ]
There are many articles available online. just follow one of them. and write some code
if you see any problem while trying so. post your problem.

Please refer Multithreading with C#[^]


#include <cstdlib>
#include <iostream>
#include <window.h>
#include <thread>


using namespace std;

int main(int argc, char *argv[])
{
    while(1);
    return 0;
}
int a,flag1=0,flag2=0;
int f1(void *)
{
    while(1)
    {
            flag2=0;
            cin>>a;
            flag1=1;
            while (flag2==0)
            sleep(100);
            flag1=0;
     }
}
int f2(void *)
{
    int sum=0,count=0;
    while(!flag1==0)
    {
        sleep(100);
        sum+=a;
        count++;
        cout<<sum/count;
        flag2=1;
     }
}


这篇关于我怎样才能使用线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆