如何在一个类中创建线程? [英] How to create a thread in a class?

查看:123
本文介绍了如何在一个类中创建线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们进行编程时是否有一个可用于创建线程的模板 OO语言?

Is there a template that can be used to create threads when we program in OO language ?

如何为OO语言设计线程包?

How to go about designing a threading package for an OO language?

推荐答案

支持

C ++ 0x将支持到目前为止,每个平台都有其自己的线程实现方式( POSIX ),但是您可以使用诸如 boost :: thread 不必担心平台特定的内容.

As of now, each platform has its own way of implementing threads (Windows, POSIX) but you can use something such as boost::thread to not have to worry about platform-specific stuff.

在Java中,有一个线程类.

In Java, there is a Thread class.

通常,要将一个类放到另一个线程中,您将在将该类传递到该线程时创建一个线程.然后线程将在该类中调用一个函数.这是一些伪C ++代码:

In general, to put a class into another thread, you will create a thread while passing that class into the thread. Then the thread will call a function in that class. Here is some pseudo-C++-code:

main()
{
    Object myObject;

    thread = CreateThread(threadFunction, myObject);

    thread.join(); // wait for thread
}

threadFunction(Object theObject)
{
    theObject.doSomething();
}

在C ++中使用boost(或C ++ 0x线程)可以简化所有操作,而Java中的Thread类可以为您处理此问题.

This is all simplified by the use of boost (or C++0x threads) in C++, and the Thread class in Java handles this for you.

线程应用程序中的一个大问题是线程同步.其中包括诸如竞赛条件

A large problem in threaded applications is synchronization of threads. This includes problems like race conditions and deadlocks, to name a couple.

存在解决这些问题的方法/对象,例如 mutex .互斥锁可以由一个线程锁定,而其他尝试锁定该互斥锁的线程将被阻塞,直到原始线程释放该互斥锁为止.

Methods/object exist to help these problems, such as a mutex. A mutex can be locked by one thread, and any other threads that try to lock the mutex will be blocked until the original thread releases the mutex.

信号量是广义互斥量.

Eric的帖子中还概述了其他有用的概念.

There are other useful concepts as outlined in Eric's post.

这篇关于如何在一个类中创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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