我如何在C++中创建线程并在主线程和另一个线程之间进行通信?
一些代码示例将会很有帮助。
我如何在C++中创建线程并在主线程和另一个线程之间进行通信?
一些代码示例将会很有帮助。
线程与其作用域共享变量,因此互斥锁非常重要。
因此,您可以通过编辑两个线程共同使用的变量来轻松进行通信:
#include <iostream>
#include <pthread.h>
main() {
pthread_t f2_thread, f1_thread;
void *f2(), *f1();
int i1;
i1 = 1;
pthread_create(&f1_thread,NULL,f1,&i1);
pthread_create(&f2_thread,NULL,f2,&i1);
pthread_join(f1_thread,NULL);
pthread_join(f2_thread,NULL);
}
void *f1(int *x){
std::cout << *x << std::endl;
}
void *f2(int *x){
sleep(1)
std::cout << ++(*x) << std::endl;
}
1
2
变量i1已在线程之间共享。这是一种通信形式,可以共享类、结构体、字符串或任何你想要的内容。
注意:这段代码几乎肯定会导致线程竞争。这只是一个示例,当在线程之间共享内存时,应始终使用同步和线程安全的做法。
std::thread
,否则使用boost::thread
。但是,在消息传递的情况下,它取决于你的问题和编程风格。boost::asio::io_service
,它非常灵活,可以发布任何类型的函数或函数对象以在其他线程的上下文中执行。使用这种技术,您不需要任何互斥锁等,还可以将线程分组到消费者和生产者,并提供许多其他有用的功能。好的,我会告诉你我知道的最简单的: _beginthread
process.h
。_endthread()
。在下面的程序中,两个线程竞争查找pi值。如果其中一个找到了pi值,它就会通知另一个线程应该结束。在main()中还打印了哪个线程找到了pi。第三个线程只是等待其他线程之一完成。
#include<process.h>
#include<windows.h> //for the Sleep()
#include<stdio.h>
volatile boolean found=false;
volatile int who=0;
void find_pi_core1(void * iterations)
{
int * ite=(int *)iterations;
for(int i=0;i<ite;i++)
{
//a sample of Monte-Carlo method here to find pi
//gets pi with more precision with additional iterations
if(found) _endthread();
}
found=true;who=1;
_endthread();
}
void find_pi_core2(void * iterations)
{
int * ite=(int *)iterations;
for(int i=0;i<ite;i++)
{
//a sample of Monte-Carlo method here to find pi
//gets pi with more precision with additional iterations
if(found) _endthread();
}
found=true;who=2;
_endthread();
}
void printscreeN(void * dummy)
{
while(!found)
{
Sleep(30); //if dont sleep, it gets a lot of cpu power
}
printf(" found! \n" );
_endthread();
}
int main()
{
Function name
^ Stack size
| ^ Function parameter
| | ^
_beginthread(find_pi_core1,0,(void *) 3000000);
_beginthread(find_pi_core2,0,(void *) 2500000);
_beginthread(printscreeN,0,(void *)0);
Sleep(3000);
if(found)
{
printf("pi has been found! core-%d has found pi first ",who);
}
else
{printf("pi has not been bound!");}
return 0;
}
线程创建是依赖于操作系统的。
在Linux上,可以使用pthread库函数pthread_create来创建线程,并使用pthread_join等待线程完成。
在Windows上,可以使用CreateThread() Windows API函数来创建线程,并使用WaitForSingleObject()函数等待线程完成。
std::thread
或boost::thread
。 - juanchopanza