qt 多线程

本文深入剖析了在瓜子聊天软件开发中使用多线程技术,尤其聚焦于Qt文档中关于多线程互斥问题的阐述。详细介绍了线程异步与同步的概念,通过具体代码示例展示了线程执行顺序的重要性,并阐述了Qt中使用QFuture进行异步操作以及QThread实现线程同步的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       这几天我们在写瓜子聊天软件,虽然我只写数据库,这个模块,因为我的任务比较轻松,为了能更好的完成任务,我看了一下多线程。

       多线程要考虑到咋们学多线程互斥的问题,就是某一资源只允许一个访问者对它进行访问,具有唯一性和排他性,但是互斥无法限制于他的访问顺序,就是因为这样,会出现错误,我看了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.
每一个线程能有自己的事件循环,有一个事件循环在线程中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值