C++ program not reaching first line of main - c++

This is main.h, I shared with you just in case there would be something wrong here. But I don't think so.
Then, there is main.cpp which is the entry point of my program.
If I generate it with Visual Studio 2017, it will compile and run without errors but it will not print anything on the console.
I can't figure out why.
main.h:
#pragma once
#include <thread>
#include "GabEngine/MainEngine.h"
#include "GraphicInterface/Console.h"
#include "GabEngine/Globals.h"
int m_ScreenWidth = 500, m_ScreenHeight = 500;
GabEngine::Wind m_RootWindow;
GabEngine::MainEngine m_MainEngine(&m_RootWindow);
Globals::NetworkStatus NetStatus;
Networking::MainNetwork m_MainNetwork(&NetStatus);
void TaskConsole();
void TaskNetwork();
main.cpp:
#include "GraphicInterface/main.h"
#include <iostream>
#undef main
void TaskConsole()
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
GabEngine::FatalError("Failed to initialize SDL");
}
m_RootWindow.Create("Utryon", m_ScreenWidth, m_ScreenHeight, 2);
m_MainEngine.InitShaders();
m_MainEngine.InitCEGUI("C:/Users/Bob/Documents/Visual Studio 2017/Projects/Utryon/GabEngine/GUI");
m_MainEngine.LoadScheme("UtryonLook.scheme");
m_MainEngine.SetFont("DejaVuSans-10");
GraphicInterface::Console MainConsole(&m_MainEngine, &m_MainNetwork);
MainConsole.InitConsole();
MainConsole.Run();
}
void TaskNetwork()
{
m_MainNetwork.Run();
}
int main(int argc, char** argv)
{
std::cout << "Here 1" << std::endl; //It is supposed to print Here 1
thread ConsoleThread(TaskConsole);
thread NetworkThread(TaskNetwork);
ConsoleThread.join();
NetworkThread.join();
// End of program
return 0;
}

Related

C + + cannot find the thread it created on ubuntu 18

I write a simple c++ code. In my code, I create two threads, then I name the two threads TCPCall30003Proc and TCPCall30004Proc, but I can not find them using top command with option -H. My os is ubuntu 18.
#include <pthread.h>
#include <thread>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <stdlib.h>
#include <chrono>
#include <unistd.h>
void f1(int num)
{
printf("1\n");
while(1)
{
sleep(1);
}
}
void f2(int num)
{
printf("2\n");
while(1)
{
sleep(1);
}
}
int main(int argc, char **argv)
{
std::thread thd_1 = std::thread(f1, 1);
std::thread thd_2 = std::thread(f2, 1);
pthread_setname_np(thd_1.native_handle(), "TCPCall30003Proc");
pthread_setname_np(thd_2.native_handle(), "TCPCall30004Proc");
while(1)
{
sleep(1);
}
return 0;
}
From the pthread_setname_np manual page:
The thread name is a meaningful C language string, whose length is restricted to 16 characters, including the terminating null byte ('\0').
[Emphasis mine]
You names are 17 characters, including the null-terminator.
If you check what pthread_setname_np returns it should return -1 and with errno set to ERANGE.
You need to shorten your names.

command spawnl() not executed

I have a code that is executable without error messages but it seems like it denies to run the code
I call by the "spawnl" command. This is my code and I receive "error=-1". I tried may different ways to solve the situation but I always receive the "-1" for an answer. I use Dev C++ compiler with 32bit release. My problem is to call the other program, sending the name of the file.
#include <stdlib.h>
#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <conio.h>
#include <process.h>
#include <ctype.h>
#include <dir.h>
#include <windows.h>
#include <dos.h>
#include <iostream>
#include <stddef.h>
void translate_to_ascii_files(),
save_mesh_data(),
make_no(),
give_names();
int load_patches(char *);
FILE *memco ;
int outnod[400] ;
float r_vector[21][21][3],cx[500],cy[500],cz[500] ;
int NOP1,NOP2; /* Number Of Points */
int patches;
char nams[26][26];
int num_of_files;
int kk,nv,nh,exnod,totnod ;
int no[4][400];
char filename[26];
void *buf;
COORD coord= {0,0};
HANDLE hConsole;
using namespace std; // std::cout, std::cin
void gotoxy(int x,int y) {
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
int main(int argc,char *argv[]) {
char com_nam[26];
int counter1,counter2,i;
int error;
system("cls");
give_names();
printf("give the final filename:");scanf("%s",filename);
for(patches=1;patches<=num_of_files;patches++) {
strcpy(com_nam,nams[patches]);
load_patches(com_nam); /* load patches for meshing*/
i=1;
for(counter1=0;counter1<=NOP1;counter1++) {
for(counter2=0;counter2<=NOP2;counter2++) {
cx[i]=r_vector[counter1][counter2][0];
cy[i]=r_vector[counter1][counter2][1];
cz[i]=r_vector[counter1][counter2][2];
i=i+1;
}
}
nh=NOP1+1;nv=NOP2+1;
make_no();
save_mesh_data();
if(argc ==1){
error=spawnl(P_WAIT,"c:\\cpprog\\unitsrf.exe","",filename,NULL);
if (error ==0) {
else {printf ("error=%d\n",error); system("PAUSE");
} }
else{gotoxy(2,11);printf("error=%s\n\n",argv[1]);
system("PAUSE");
}
} translate_to_ascii_files();
}

No sound when using SDL_Mixer in C++/Linux

I'm trying to use SDL_mixer in C++ under Linux to play sounds asynchronously, but it somehow doesn't work. When I execute it, no sound is playing at all. I'm not quite familiar with SDL and classes though, so it would be very helpful if someone could detect where the error in my code is.
My header file (sample.h):
#pragma once
#include <string>
#include <memory>
#include "SDL_mixer.h"
class sample {
public:
sample(const std::string &path, int volume);
void play();
void play(int times);
void set_volume(int volume);
private:
std::unique_ptr<Mix_Chunk, void (*)(Mix_Chunk *)> chunk;
};
My main program (.cpp):
#include "sample.h"
#include <iostream>
sample::sample(const std::string &path, int volume) : chunk(Mix_LoadWAV(path.c_str()), Mix_FreeChunk) {
if (!chunk.get()) {
std::cout << "Could not load audio sample: " << path << std::endl;
}
Mix_VolumeChunk(chunk.get(), volume);
}
void sample::play() {
Mix_PlayChannel(-1, chunk.get(), 0);
}
void sample::play(int times) {
Mix_PlayChannel(-1, chunk.get(), times - 1);
}
void sample::set_volume(int volume) {
Mix_VolumeChunk(chunk.get(), volume);
}
int main() {
if (Mix_Init(MIX_INIT_FLAC | MIX_INIT_MP3 | MIX_INIT_OGG) < 0) {
return -1;
}
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) < 0) {
std::cout << "Can not initialize mixer!" << std::endl;
return -1;
}
// Amount of channels (Max amount of sounds playing at the same time)
Mix_AllocateChannels(32);
sample s("Snare-Drum-1.wav", MIX_MAX_VOLUME / 2);
s.play();
Mix_Quit();
return 0;
}
Your binary runs and finishes before phaffing about long enough to render the audio so solution is to make the code remain running longer ... I got your code working by adding this
s.play();
std::chrono::milliseconds timespan(2000); // or whatever
std::this_thread::sleep_for(timespan);
in your header replace
#include "SDL_mixer.h"
with
#include <SDL2/SDL_mixer.h>
#include <chrono>
#include <thread>
so now its compiled using SDL2 and not SDL
g++ -o sample sample.cpp -lSDL2 -lSDL2_mixer
So .... what is the real SDL2 solution ? well I would say a typical use case is SDL2 is part of a game which remains running hence the code base has an event loop which remains active long enough to hear the audio getting rendered. Another solution short of explicitly using a sleep or a gui is to put the code into a server ... SDL2 api itself must have their one-liner as well

Using boost library with Intel Pin

I am trying to use the Boost 1.60.0 library with Intel Pin 2.14-71313-msvc12-windows. The following piece of code is the simple implementation I did to try things out:
#define _CRT_SECURE_NO_WARNINGS
#include "pin.H"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <time.h>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace boost_network{
#include <boost/asio.hpp>
#include <boost/array.hpp>
}
//Buffersize of lockfree queue to use
const int BUFFERSIZE = 1000;
//Tracefiles for error / debug purpose
std::ofstream TraceFile;
//String wrapper for boost queue
class statement {
public:
statement(){ s = ""; }
statement(const std::string &n) : s(n) {}
std::string s;
};
//string queue to store inserts
boost::lockfree::spsc_queue<statement, boost::lockfree::capacity<BUFFERSIZE>> buffer; // need lockfree queue for multithreading
//Pin Lock to synchronize buffer pushes between threads
PIN_LOCK lock;
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "calltrace.txt", "specify trace file name");
KNOB<BOOL> KnobPrintArgs(KNOB_MODE_WRITEONCE, "pintool", "a", "0", "print call arguments ");
INT32 Usage()
{
cerr << "This tool produces a call trace." << endl << endl;
cerr << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
VOID ImageLoad(IMG img, VOID *)
{
//save module informations
buffer.push(statement("" + IMG_Name(img) + "'; '" + IMG_Name(img).c_str() + "'; " + IMG_LowAddress(img) + ";"));
}
VOID Fini(INT32 code, VOID *v)
{
}
void do_somenetwork(std::string host, int port, std::string message)
{
boost_network::boost::asio::io_service ios;
boost_network::boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
boost_network::boost::asio::ip::tcp::socket socket(ios);
socket.connect(endpoint);
boost_network::boost::system::error_code error;
socket.write_some(boost_network::boost::asio::buffer(message.data(), message.size()), error);
socket.close();
}
void WriteData(void * arg)
{
int popped; //actual amount of popped objects
const int pop_amount = 10000;
statement curr[pop_amount];
string statement = "";
while (1) {
//pop more objects from buffer
while (popped = buffer.pop(curr, pop_amount))
{
//got new statements in buffer to insert into db: clean up statement
statement.clear();
//concat into one statement
for (int i = 0; i < popped; i++){
statement += curr[i].s;
}
do_somenetwork(std::string("127.0.0.1"), 50000, sql_statement.c_str());
}
PIN_Sleep(1);
}
}
int main(int argc, char *argv[])
{
PIN_InitSymbols();
//write address of label to TraceFile
TraceFile.open(KnobOutputFile.Value().c_str());
TraceFile << &label << endl;
TraceFile.close();
// Initialize the lock
PIN_InitLock(&lock);
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
// Register ImageLoad to be called when an image is loaded
IMG_AddInstrumentFunction(ImageLoad, 0);
//Start writer thread
PIN_SpawnInternalThread(WriteData, 0, 0, 0);
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
When I build the above code, Visual Studio cannot find boost_network::boost::asio::ip and keeps giving error saying asio::ip does not exist. I had previously posted this question myself:
Sending data from a boost asio client
and after using the provided solution in the same workspace, the code worked fine and I was able to communicate over the network. I am not sure what is going wrong here. For some reason using the different namespace seems to not work out because it says boost must be in the default namespace.
However, if I do not add the namespace, in that case the line,
KNOB<BOOL> KnobPrintArgs(KNOB_MODE_WRITEONCE, "pintool", "a", "0", "print call arguments ");
throws an error saying BOOL is ambiguous.
Kindly suggest what should be a viable solution in this situation. I am using Visual Studio 2013.
The same piece of code with only Pin also works with out the network part and I can write data generated from Pin into a flat file.

Lost prints from pthread c++

I start to use pthread of C++ and have made a simple exampe for multi threads(3). But what i see is that I always got prints from two threads. why?
#include <iostream>
#include <string>
#include <pthread.h>
using namespace std;
int N=10;
void* run(void* arg) {
char* msg = (char*)arg;
for(int i; i<=N; ++i) std::cout<<msg<<std::endl;
}
int main(int argc, char* argv[]) {
if (argc > 1) N = stoi(argv[1]);
pthread_t t1,t2,t3;
pthread_create(&t1,NULL,run,(void*)"xxx");
pthread_create(&t2,NULL,run,(void*)" howdy");
pthread_create(&t3,NULL,run,(void*)" wrold");
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
return 0;
}
Prints like:
howdy
wrold
howdy
wrold
It's undefined behaviour, anything can happen.
For example on my machine it doesn't print anything at all.
i is not initialized.
void* run has to return something (e.g.: return NULL;)