这几天我们在写瓜子聊天软件,虽然我只写数据库,这个模块,因为我的任务比较轻松,为了能更好的完成任务,我看了一下多线程。
多线程要考虑到咋们学多线程互斥的问题,就是某一资源只允许一个访问者对它进行访问,具有唯一性和排他性,但是互斥无法限制于他的访问顺序,就是因为这样,会出现错误,我看了qt文档,我觉得它描述这个问题写的不错,
For example, say there is a method that prints a message to the user on two lines:
int number = 6;
void method1()
{
number *= 5;
number /= 4;
}
void method2()
{
number *= 3;
number /= 2;
}
If these two methods are called in succession, the following happens:
// method1()
number *= 5; // number is now 30
number /= 4; // number is now 7
// method2()
number *= 3; // number is now 21
number /= 2; // number is now 10
If these two methods are called simultaneously from two threads then the following sequence could result:
// Thread 1 calls method1()
number *= 5; // number is now 30
// Thread 2 calls method2().
//
// Most likely Thread 1 has been put to sleep by the operating
// system to allow Thread 2 to run.
number *= 3; // number is now 90
number /= 2; // number is now 45
// Thread 1 finishes executing.
number /= 4; // number is now 11, instead of 10
现在还有线程异步,在qt中用Qfuture完成
还有线程的同步,
This will create a QTcpSocket in the thread and then execute the thread's event loop. Use the start() method to begin execution. Execution ends when you return from run(), just as an application does when it leaves main(). QThread will notifiy you via a signal when the thread isstarted(), finished(), and terminated(), or you can use isFinished() and isRunning() to query the state of the thread. Use wait() to block until the thread has finished execution.
Each QThread can have its own event loop. You can start the event loop by calling exec(); you can stop it by calling exit() or quit(). Having an event loop in a thread makes it possible to connect signals from other threads to slots in this thread, using a mechanism called queued connections. It also makes it possible to use classes that require the event loop, such as QTimer and QTcpSocket, in the thread. Note, however, that it is not possible to use any widget classes in the thread.
每一个线程能有自己的事件循环,有一个事件循环在线程中