我是C++ pthreads的新手.我正在尝试做的是使用一个线程来捕获UDP数据包并将其放入队列,另一个线程用于处理它们并在之后发送它们.我的问题是,如何在单独的线程中将元素推入/移出容器?
这是一个例子:
#include <queue>
#include <iostream>
#include <pthread.h>
#include <signal.h>
class A{
public:
A(){
pthread_create(&thread, NULL, &A::pushQueue, NULL);
pthread_join(thread, NULL);
}
virtual ~A(){
pthread_kill(thread, 0);
}
private:
static void* pushQueue(void* context){
for(int i = 0; i < 10; i++){
bufferInbound.push(i);
std::cout << i << " pushed!" << std::endl;
}
}
static std::queue<int> bufferInbound;
pthread_t thread;
};
int main(){
A* a = new A();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,它给了我以下结果:
U53R@Foo:~/$ make
g++ -g -lpthread main.cpp -c
g++ -g -lpthread main.o -o …Run Code Online (Sandbox Code Playgroud) 我正在使用 libevent 编写一个事件驱动的应用程序,并且需要使用 libusb-1.0 进行 USB 传输。
我想使用libusb_get_pollfds获取文件描述符列表(在 中fds)并将它们添加到 libevent,如下所示:
const struct libusb_pollfd **fds = libusb_get_pollfds(device->context);
const struct libusb_pollfd *it = *fds;
for(;it != NULL; ++it) {
cout << "Adding fd: " << it->fd << ", " << it->events << endl;
struct event * ev = event_new(base_,
it->fd, it->events | EV_PERSIST,
callbacks::libusb_cb, this);
event_add(ev, 0);
libusb_fds_events.insert(std::make_pair(it->fd, ev));
}
free(fds);
// (...)
// And the callback function:
void callbacks::libusb_cb(evutil_socket_t fd, short what, void *arg) {
Server *s …Run Code Online (Sandbox Code Playgroud)