abort() has been called after thread - c++

I am making an autoclicker with a gui in which I have a thread, but whenever I try to run it it gives me an error with abort() has been called. The breakpoint is below the line where the first thread is called. I am very new to multi-threading so I don't really know what the problem is, this is my code:
#include "AutoClicker.h"
#include <thread>
#include <iostream>
#include <conio.h>
#include <Windows.h>
#include <chrono>
using namespace std::chrono_literals;
AutoClicker::AutoClicker()
{
std::thread loop (&AutoClicker::autoClickerMain, this);
}
AutoClicker::~AutoClicker()
{
}
void AutoClicker::setCPS(int cpsIn)
{
delay = 1000 / cpsIn;
}
void AutoClicker::setHotkey(char hotkeyChar)
{
hotkey = static_cast<int>(hotkeyChar);
}
void AutoClicker::autoClickerMain()
{
int c = 0;
std::thread clicker(&AutoClicker::Clicker, this);
while (1)
{
c = 0;
c = _getch();
if (c == hotkey)
{
running = !running;
}
}
}
void AutoClicker::Clicker()
{
while (1)
{
if (running)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
}
}
}

Related

Producer-Consumer Problem in c++ using pthread

I am currently learning multithreading and semaphores and have been assigned to recreate the problem using only pthread. I found a solution that uses std::thread and have been working to convert it to pthreads, but I am having problems with the pthread_create method.
I am not sure specifically how to turn this statement
pthread_create(&threads[i], NULL, &Producer::run, &p);
into something that works with pthreads.
Here is my whole code for reference
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <deque>
#include <condition_variable>
#include <semaphore.h>
#include <queue>
#ifdef _WIN32
#include <windows.h>
void sleeps(unsigned milliseconds)
{
Sleep(milliseconds);
}
#else
#include <unistd.h>
void sleeps(unsigned milliseconds) {
usleep(milliseconds * 1000); // takes microseconds
}
#endif
class Widget {
public:
int data;
void setData(int data) {
this->data = data;
}
};
class Buffer
{
public:
void add(Widget widget) {
while (true) {
pthread_mutex_lock(&lock);
sharedBuffer.push_back(widget);
pthread_mutex_unlock(&lock);
return;
}
}
Widget remove() {
while(true) {
pthread_mutex_lock(&lock);
Widget backElem = sharedBuffer.back();
sharedBuffer.pop_back();
pthread_mutex_unlock(&lock);
return backElem;
}
}
Buffer() {}
private:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
std::deque<Widget> sharedBuffer;
};
class Producer{
Buffer& sharedBuffer;
pthread_mutex_t coutMut;
public:
Producer(Buffer& buffer)
: sharedBuffer(buffer), coutMut(PTHREAD_MUTEX_INITIALIZER)
{}
void run() {
while(true) {
Widget widget;
widget.setData(rand() % 10);
sharedBuffer.add(widget);
pthread_mutex_lock(&coutMut);
std::cout << "Added: " << widget.data << "\n";
sleeps(50);
pthread_mutex_unlock(&coutMut);
}
}
};
class Consumer
{
Buffer& sharedBuffer;
pthread_mutex_t coutMut;
public:
Consumer(Buffer& buffer)
: sharedBuffer(buffer), coutMut(PTHREAD_MUTEX_INITIALIZER)
{}
void run() {
while(true) {
Widget widget;
widget = sharedBuffer.remove();
pthread_mutex_lock(&coutMut);
std::cout << "Removed: " << widget.data << "\n";
sleeps(50);
pthread_mutex_unlock(&coutMut);
}
}
};
int main(int argc, char *argv[]) {
typedef std::string string_std;
const int producerT = std::stoi(argv[1]);
const int consumerT = std::stoi(argv[2]);
int threadSize = producerT + consumerT;
pthread_t threads[threadSize];
void *status;
Buffer b1;
Producer p(b1);
Consumer c(b1);
for (int i = 0; i < producerT; i++) {
pthread_create(&threads[i], NULL, &Producer::run, &p);
}
for (int i = producerT; i < threadSize; i++) {
pthread_create(&threads[i], NULL, &Consumer::run, &c);
}
sleeps(5000);
for (int i = 0; i < threadSize; i++) {
pthread_join(threads[i], &status);
}
exit(0);
}
You are probably looking for something like this:
class Producer {
static void static_run(void* pThis) {
static_cast<Producer*>(pThis)->run();
}
void run() {
// Real work done here.
}
};
// At call site
Producer p;
pthread_create(&threads[i], NULL, Producer::static_run, &p);
The point is that pthread_create wants a C-style function - either a standalone non-member function, or a static member function. So you need an adapter (sometimes referred to as a "trampoline") that satisfies the requirements, and then turns around and calls the member function.

Qtimer doesn`t work. I think it is not updated

I want send udp packet every 10ms.
I created QTimer, but SLOT doesn`t work.
I created infinite loop with the output is timer->remainingTime() and it looks like the timer doesn't want to reset.
In output:
10
10
10
...
9
9
9
...
...
...
1
1
1
...
0
0
0
0
0
0
and then some zeros. Maybe this method is absolutely wrong. How can I still do it?
It`s my code:
usingbks.h
#ifndef USINGBKS_H
#define USINGBKS_H
#include "bks.h"
#include "sendtimer.h"
#include <stdlib.h>
#include <QtNetwork>
#include <thread>
class UsingBKS : public QObject
{
Q_OBJECT
private slots:
void sendPackets();
private:
QTimer* timer = new QTimer(this);
QUdpSocket* socket = new QUdpSocket(this);
...
int TrandmissionStart(QString ip, quint16 port);
int SendBKSOutBKSCond();
int SendBKSOutPrimaKVCond2();
};
#endif // USINGBKS_H
usingbks.cpp
UsingBKS::UsingBKS()
{
}
UsingBKS::~UsingBKS()
{
delete socket;
delete timer;
}
void UsingBKS::sendPackets() {
SendBKSOutBKSCond();
SendBKSOutPrimaKVCond2();
}
...
int UsingBKS::TrandmissionStart(QString ip, quint16 port)
{
socket->connectToHost(QHostAddress(ip), port);
connect(timer, SIGNAL(timeout()), this, SLOT(sendPackets()));
timer->start(1000);
while(1) { //it`s only for test
std::cout << timer->remainingTime() << " " << timer->isActive() << std::endl;
}
return 1;
}
main.cpp
#include <QCoreApplication>
#include <QObject>
#include <QTimer>
#include <iostream>
#include <stdlib.h>
#include "usingbks.h"
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
unsigned int Hz100 = 0, kHz1, kHz10, kHz100, MHz1, MHz10 ;
Hz100 = 1;
kHz1 = 1;
kHz10 = 1;
kHz100 = 1;
MHz1 = 1;
MHz10 = 1;
UsingBKS* bks = new UsingBKS ();
bks->SetBKSOutBKSCond(4, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0);
bks->SetBKSOutPrimaKVCond2(4, 12,
static_cast<uint8_t>(Hz100),
static_cast<uint8_t>(kHz1),
static_cast<uint8_t>(kHz10),
static_cast<uint8_t>(kHz100),
static_cast<uint8_t>(MHz1),
static_cast<uint8_t>(MHz10), 0);
cout << bks->TrandmissionStart("1.1.1.1", 10310);
cout << "Trandmission started." << endl;
delete bks;
return a.exec();
}

"QObject::~QObject: Timers cannot be stopped from another thread" in C++

I got the problem about timers which is
QObject::~QObject: Timers cannot be stopped from another thread
Below is the log data from my terminal.
$ ./boost_tutorials
init done
All done. Exit safely!
QObject::~QObject: Timers cannot be stopped from another thread
Here is my C++ code with thread from boost. I build it via CMakeLists.
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
#include <opencv2/opencv.hpp>
class Robot {
public:
Robot() {
cap.open(-1);
SYSTEM_QUIT = false;
if (!cap.isOpened()) {
cout << "Error opening the video" << endl;
SYSTEM_QUIT = true;
}
}
~Robot() {
destroyAllWindows();
cout << "All done. Exit safely!" << endl;
}
void run() {
boost::thread* t1 = new boost::thread(boost::bind(&Robot::imageProcCallback, this));
boost::thread* t2 = new boost::thread(boost::bind(&Robot::simpleCallback, this));
t1->join();
t2->join();
}
void imageProcCallback() {
Mat frame;
int cc = 0;
while(!SYSTEM_QUIT) {
cap >> frame;
if (!msgs.empty()) {
Point pt(rand()%frame.cols, rand()%frame.rows);
putText(frame, msgs.back(), pt, cv::FONT_HERSHEY_COMPLEX, 2, Scalar(0, 255, 0));
}
imshow(filename, frame);
if (waitKey(5) == 27)
SYSTEM_QUIT = true;
}
frame.release();
}
void simpleCallback() {
while(!SYSTEM_QUIT) {
int count = rand() % 100;
std::string str = std::to_string(count);
msgs.push_back(str);
}
}
private:
string filename;
VideoCapture cap;
bool SYSTEM_QUIT;
std::vector<std::string> msgs;
};
void main() {
Robot robot;
robot.run();
}

Unhandled exception error Visual Studio 2012 and Allegro 4

I´m using allegro 4.4.2 on Visual Studio 2012 for a school project. Allegro is installed and working, and I'm trying to get it to load a map.txt file which is located in the project folder. When debugging, allegro freezes and becomes incredibly slow and throws an unhandled exception, violation access code at me.
This is Map.h:
#include <allegro.h>
#include "Global.h"
#include <fstream>
using namespace std;
class Map
{
public:
Map();
~Map();
void Init();
void Update();
void Draw(BITMAP *Buffer);
void LoadMap (const char*filename);
private:
int loadCounterX;
int loadCounterY;
int mapSizeX;
int mapSizeY;
int MapFile[20][15];
};
And this is Map.cpp:
#include "Map.h"
Map::Map()
{
}
Map::~Map()
{
}
void Map::Init()
{
loadCounterX = loadCounterY = 0;
Map::LoadMap("map1.txt");
}
void Map::Update()
{
}
void Map::Draw(BITMAP *Buffer)
{
for (int i = 0; 1 < mapSizeX; i++)
{
for (int j = 0; j < mapSizeY; j++)
{
if (MapFile[i][j] == 1)
{
rectfill(Buffer, i*BlockSize, j*BlockSize, i*BlockSize + BlockSize, j*BlockSize + BlockSize, makecol(0, 255, 255));
}
else if (MapFile[i][j] == 2)
{
rectfill(Buffer, i*BlockSize, j*BlockSize, i*BlockSize + BlockSize, j*BlockSize + BlockSize, makecol(0, 255, 0));
}
}
}
}
void Map::LoadMap(const char*filename)
{
ifstream openfile (filename);
if (openfile.is_open())
{
openfile >> mapSizeX >> mapSizeY;
while (!openfile.eof())
{
openfile >> MapFile[loadCounterX][loadCounterY];
loadCounterX ++;
if (loadCounterX >= mapSizeX)
{
loadCounterX = 0;
loadCounterY ++;
}
}
loadCounterX = loadCounterY = 0;
} //File is opened
else
{
allegro_message ("Map File couldn't be found");
}
}
and here is my main file:
#include <allegro.h>
#include "Player.h"
#include "Global.h"
#include "Camera.h"
#include "Map.h"
using namespace std;
volatile int counter = 0;
void Increment ()
{
counter ++;
}
int main (void)
{
allegro_init();
install_keyboard();
install_mouse();
install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, "A");
set_color_depth(32);
set_gfx_mode (GFX_AUTODETECT_WINDOWED, ScreenWidth, ScreenHeight, 0, 0);
LOCK_VARIABLE (counter);
LOCK_FUNCTION (Increment);
install_int_ex (Increment, BPS_TO_TIMER(100));
BITMAP *Buffer = create_bitmap (6000, ScreenHeight);
bool done = false;
Player player;
Camera camera;
Map map;
player.Init();
camera.Init();
map.Init();
while (!done)
{
while (counter > 0)
{
//Input
if (key[KEY_ESC])
done = true;
//Update
map.Update();
player.Update();
camera.Update(player.x, player.y);
counter --;
}
//Draw
map.Draw(Buffer);
player.Draw(Buffer);
camera.Draw(Buffer);
clear_bitmap(Buffer);
}
return 0;
}
END_OF_MAIN();
It crashes at this line
if (MapFile[i][j] == 1)
everytime. All of the variables shown in "Autos" in Visual Studio turn red; "MapFile" "MapFile[i]" (which I don't understand.. shouldn't this just be "i"?) "j" "mapSizeY" and "this" However when I expand the "MapFile", the first 20 blocks are filled out correctly as they are in my map.txt file.
I'm completely lost and have no idea what to do... any help is greatly appreciated!
In void Map::Draw(BITMAP *Buffer) you use 1 < mapSizeX instead of i < mapSizeX.
You might also want to prevent calling Map::Draw when the Map::LoadMap wasn't called before.

XNextEvent Doesn't works for some reason

I'm trying to catch keypress events using XLib. But for some reasons XNextEvent not working.
I'm not receiving any errors, but it looks like my program stuck on the line of "XNextEvent" call.
Here is my code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;
int main()
{
XEvent event;
KeySym key;
char text[255];
Display *dis;
dis = XOpenDisplay(NULL);
while (1) {
XNextEvent(dis, &event);
if (event.type==KeyPress && XLookupString(&event.xkey,text,255,&key,0) == 1) {
if (text[0]=='q') {
XCloseDisplay(dis);
return 0;
}
printf("You pressed the %c key!\n", text[0]);
}
}
return 0;
}
This is not how X11 windowing system works.
Read this carefully. The key point is :
The source of the event is the viewable window that the pointer is in.
You do not create a window, therefore your program doesn't receive keyboard events. Even if you created window, it has to have focus :
The window used by the X server to report these events depends on the window's position in the window hierarchy and whether any intervening window prohibits the generation of these events.
Working example
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;
int main()
{
XEvent event;
Display *dis;
Window root;
Bool owner_events = False;
unsigned int modifiers = ControlMask | LockMask;
dis = XOpenDisplay(NULL);
root = XDefaultRootWindow(dis);
unsigned int keycode = XKeysymToKeycode(dis, XK_P);
XSelectInput(dis,root, KeyPressMask);
XGrabKey(dis, keycode, modifiers, root, owner_events, GrabModeAsync, GrabModeAsync);
while (1) {
Bool QuiteCycle = False;
XNextEvent(dis, &event);
if (event.type == KeyPress) {
cout << "Hot key pressed!" << endl;
XUngrabKey(dis, keycode, modifiers, root);
QuiteCycle = True;
}
if (QuiteCycle) {
break;
}
}
XCloseDisplay(dis);
return 0;
}