I'd like to test this function with Google Test:
foo() {
if(some_grave_error)
exit(1);
// do something
}
I want my test to fail if foo calls std::exit(). How do I do this? It is sort of inverse to what EXPECT_EXIT does?
You should make foo() testable:
using fexit_callback = void(*)(int);
void foo(fexit_callback exit = &std::exit)
{
if(some_condition)
exit(1);
}
And magically, all your troubles disappear:
#include <cstdlib>
#include <cassert>
using fexit_callback = void(*)(int);
void foo(fexit_callback exit = &std::exit)
{
if(true)
exit(1);
}
namespace mockup
{
int result = 0;
void exit(int r) { result = r; }
}
int main()
{
foo(mockup::exit);
assert(mockup::result == 1);
}
Related
I wonder whether I can use the side effects of a conditional_variable test?
Is it guaranteed that the conditional_variable test is returning to execution if it returns true, or can there be the situation that the test returns
true, but it is called again or times out in between?
In the below example maybeCmd_locked() de-queues a cmd, however I want to
avoid that it is called 2 times for one exit of the conditional_variable wait:
if (cv.wait_until(lk, now + 100ms, [&cmd,this]{ return ((cmd = maybeCmd_locked()) != -1); }))
//g++ test.cpp -o test.exe -lstdc++ -lpthread
#include <stdlib.h>
#include <stdio.h>
#include <thread>
#include <queue>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std::literals::chrono_literals;
class eventLooper {
public:
eventLooper() : threadexit(false) {};
bool threadexit;
std::queue<int> cmds;
std::mutex m;
std::condition_variable cv;;
int maybeCmd_locked()
{
if (cmds.size() > 0) {
int cmd = cmds.front();
cmds.pop();
return cmd;
}
return -1;
}
int getNextCmd(void)
{
int cmd = -1;
std::unique_lock<std::mutex> lk(m);
auto now = std::chrono::system_clock::now();
if (cv.wait_until(lk, now + 100ms, [&cmd,this]{ return ((cmd = maybeCmd_locked()) != -1); }))
{
return cmd;
}
return -1;
}
int sendCmd(int cmd)
{
std::lock_guard<std::mutex> lock(m);
cmds.push(cmd);
cv.notify_one();
return 0;
}
void run(void)
{
int cmd;
printf("run\n");
std::this_thread::sleep_for(std::chrono::milliseconds(10));
while (!threadexit)
{
cmd = getNextCmd();
if (cmd == -1) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} else {
printf("cmd received: %d\n", cmd);
}
}
}
};
eventLooper e;
int main(int argc, char **argv)
{
(void) argc;
(void) argv;
std::thread n(&eventLooper::run, &e);
for (int i = 0; i < 10; i++)
{
std::this_thread::sleep_for(1000ms);
e.sendCmd(i);
}
std::this_thread::sleep_for(1000ms);
e.threadexit = true;
n.join();
printf("exit\n");
return 0;
}
The predicate is always checked under the lock, and another wait isn't done if the predicate returns true. In a simplifed version of your code (which doesn't have time outs) is:
if (cv.wait(lk, [&cmd,this]{ return ((cmd = maybeCmd_locked()) != -1); }))
{
return cmd;
}
cv.wait(lock, pred) is defined to be equivalent of:
while(!pred())
{
wait(lock);
}
In this case you can see that your predicate cannot be called twice if it returns true the first time.
Adding the timeout to the question doesn't change how this work. cv.wait_until(...) is the equivalent of:
while (!pred()) {
if (wait_until(lock, timeout_time) == std::cv_status::timeout) {
return pred();
}
}
Again, its clear that what you're worried about cannot happen.
I have function that returns me a value. I want to use threads for doSth function and set returning value for variables above, here is an example:
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// func for execution
int doSth(int number)
{
return number;
}
int main()
{
// some code ...
int numberOne; // no value now, but in thread I want to set a value from it
int numberTwo; // depending on function input value
thread t1(doSth, 1); // set numberOne = 1;
thread t2(doSth, 2); // set numberTwo = 2;
// wait them to execute
t1.join();
t2.join();
// now I should have numberOne = 1; numberTwo = 2
// some code ...
return 0;
}
How could I do it?
How to return value from std::thread
Besides std::async shown in other answers, you can use std::packaged_task:
std::packaged_task<int(int)> task{doSth};
std::future<int> result = task.get_future();
task(1);
int numberOne = result.get();
This allows separating creation of the task, and executing it in case that is needed.
Method 1: Using std::async (higher-level wrapper for threads and futures):
#include <thread>
#include <future>
#include <iostream>
int func() { return 1; }
int main(){
std::future<int> ret = std::async(&func);
int i = ret.get();
std::cout<<"I: "<<i<<std::endl;
return 0;
}
Method 2: Using threads and futures:
#include <thread>
#include <future>
#include <iostream>
void func(std::promise<int> && p) {
p.set_value(1);
}
int main(){
std::promise<int> p;
auto f = p.get_future();
std::thread t(&func, std::move(p));
t.join();
int i = f.get();
std::cout<<"I: "<<i<<std::endl;
return 0;
}
My prefered method is encapsulate the call in a specific method returning nothing (and managing error in the same way).
void try_doSth(int number, int* return_value, int* status)
{
try
{
*return_value = doSth(number);
*status = 0;
}
catch(const std::exception& e) { *status = 1; }
catch(...) { *status = 2; }
}
int r1,r2,s1,s2;
std::thread t1(try_doSth, 1, &r1, &s1);
std::thread t2(try_doSth, 2, &r2, &s2);
I know how to use it in C (with signal.h), but the <csignal> library is provided in C++ and I want to know if it includes sigaction? I tried running it but it said not found. I was wondering if I did something wrong?
#include <iostream>
#include <string>
#include <cstdio>
#include <csignal>
namespace {
volatile bool quitok = false;
void handle_break(int a) {
if (a == SIGINT) quitok = true;
}
std::sigaction sigbreak;
sigbreak.sa_handler = &handle_break;
sigbreak.sa_mask = 0;
sigbreak.sa_flags = 0;
if (std::sigaction(SIGINT, &sigbreak, NULL) != 0) std::perror("sigaction");
}
int main () {
std::string line = "";
while (!::quitok) {
std::getline(std::cin, line);
std::cout << line << std::endl;
}
}
But for some reason it doesn't work.
EDIT:
By "doesn't work", I mean the compiler fails and says there's no std::sigaction function or struct.
sigaction is C POSIX isn't it?
sigaction is in POSIX, not the C++ standard, and it's in the global namespace.
You'll also need the struct keyword to differentiate between sigaction, the struct,
and sigaction, the function.
Finally, the initialization code will need to be in a function -- you can't have it
in file scope.
#include <cstdio>
#include <signal.h>
namespace {
volatile sig_atomic_t quitok = false;
void handle_break(int a) {
if (a == SIGINT) quitok = true;
}
}
int main () {
struct sigaction sigbreak;
sigbreak.sa_handler = &handle_break;
sigemptyset(&sigbreak.sa_mask);
sigbreak.sa_flags = 0;
if (sigaction(SIGINT, &sigbreak, NULL) != 0) std::perror("sigaction");
//...
}
Have any one tried anything like this?
Is it possible to print the value of a string or integer on the program itself? Say for example - I have written 2 tests for a program I am trying to call all the tests functions by looping over in a for loop.
A small sample example
#define MAX_TESTS 10
for(test_idx = 0; test_idx<MAX_TESTS; ++test_idx)
{
test_##test_idx();
//Here the output will be more like "test_test_idx();"
//But I am looking for something like
//"test_0();"
//"test_1();"
//"test_2();"
.
.
.
//"test_9();"
}
Is there a way to do it in C?
Complete Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Macros
#define MAX_TEST 2
#define _MYCAT(a,b) a##b()
void test_0()
{
printf("Test 0\n");
}
void test_1()
{
printf("Test 1 \n");
}
int main()
{
printf("Max Product Testing \n");
for (int test_idx=0; test_idx<MAX_TEST; ++test_idx)
{
/* Try - 1
char buffer[50];
int n = sprintf(buffer, "test_%d", test_idx);
printf("%s %d \n", buffer, n);
*/
//Try - 2
//_MYCAT(test_, test_idx);
}
return 0;
}
The closet you can get in C++ is to keep a map of function names to functions as follows:
#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>
using namespace std;
void test_0()
{
printf("Test 0\n");
}
void test_1()
{
printf("Test 1 \n");
}
int main() {
unordered_map<string, function<void()>> func_map;
func_map["test_0"] = test_0;
func_map["test_1"] = test_1;
for(int i = 0; i < 2; ++i) {
func_map.at("test_" + to_string(i))();
}
return 0;
}
You can make an array of function pointers and call each one in a loop.
Example:
#include <stdio.h>
void test_0()
{
printf("Test 0\n");
}
void test_1()
{
printf("Test 1\n");
}
void test_2()
{
printf("Test 2\n");
}
int main()
{
void(*a)() = test_0;
void(*b)() = test_1;
void(*c)() = test_2;
const int SIZE = 3;
void(*arr[SIZE])() = {
{ a }, { b }, { c }
};
for (int i = 0; i < SIZE; ++i) {
arr[i]();
}
return 0;
}
Output:
Test 0
Test 1
Test 2
I am reading a message from a socket with C++ code and am trying to plot it interactively with matplotlib, but it seems Python code will block the main thread, no matter I use show() or ion() and draw(). ion() and draw() won't block in Python.
Any idea how to plot interactively with matplotlib in C++ code?
An example would be really good.
Thanks a lot.
You may also try creating a new thread that does the call to the
blocking function, so that it does not block IO in your main program
loop. Use an array of thread objects and loop through to find an unused
one, create a thread to do the blocking calls, and have another thread
that joins them when they are completed.
This code is a quick slap-together I did to demonstrate what I mean about
using threads to get pseudo asynchronous behavior for blocking functions...
I have not compiled it or combed over it very well, it is simply to show
you how to accomplish this.
#include <pthread.h>
#include <sys/types.h>
#include <string>
#include <memory.h>
#include <malloc.h>
#define MAX_THREADS 256 // Make this as low as possible!
using namespace std;
pthread_t PTHREAD_NULL;
typedef string someTypeOrStruct;
class MyClass
{
typedef struct
{
int id;
MyClass *obj;
someTypeOrStruct input;
} thread_data;
void draw(); //Undefined in this example
bool getInput(someTypeOrStruct *); //Undefined in this example
int AsyncDraw(MyClass * obj, someTypeOrStruct &input);
static void * Joiner(MyClass * obj);
static void * DoDraw(thread_data *arg);
pthread_t thread[MAX_THREADS], JoinThread;
bool threadRunning[MAX_THREADS], StopJoinThread;
bool exitRequested;
public:
void Main();
};
bool MyClass::getInput(someTypeOrStruct *input)
{
}
void MyClass::Main()
{
exitRequested = false;
pthread_create( &JoinThread, NULL, (void *(*)(void *))MyClass::Joiner, this);
while(!exitRequested)
{
someTypeOrStruct tmpinput;
if(getInput(&tmpinput))
AsyncDraw(this, tmpinput);
}
if(JoinThread != PTHREAD_NULL)
{
StopJoinThread = true;
pthread_join(JoinThread, NULL);
}
}
void *MyClass::DoDraw(thread_data *arg)
{
if(arg == NULL) return NULL;
thread_data *data = (thread_data *) arg;
data->obj->threadRunning[data->id] = true;
// -> Do your draw here <- //
free(arg);
data->obj->threadRunning[data->id] = false; // Let the joinThread know we are done with this handle...
}
int MyClass::AsyncDraw(MyClass *obj, someTypeOrStruct &input)
{
int timeout = 10; // Adjust higher to make it try harder...
while(timeout)
{
for(int i = 0; i < MAX_THREADS; i++)
{
if(thread[i] == PTHREAD_NULL)
{
thread_data *data = (thread_data *)malloc(sizeof(thread_data));
if(data)
{
data->id = i;
data->obj = this;
data->input = input;
pthread_create( &(thread[i]), NULL,(void* (*)(void*))MyClass::DoDraw, (void *)&data);
return 1;
}
return 0;
}
}
timeout--;
}
}
void *MyClass::Joiner(MyClass * obj)
{
obj->StopJoinThread = false;
while(!obj->StopJoinThread)
{
for(int i = 0; i < MAX_THREADS; i++)
if(!obj->threadRunning[i] && obj->thread[i] != PTHREAD_NULL)
{
pthread_join(obj->thread[i], NULL);
obj->thread[i] = PTHREAD_NULL;
}
}
}
int main(int argc, char **argv)
{
MyClass base;
base.Main();
return 0;
}
This way you can continue accepting input while the draw is occurring.
~~Fixed so the above code actually compiles, make sure to add -lpthread