Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Don't know if this is in the right thread but I'm trying to compile something and I don't understand what this line does.

quote:

/bin/bash ../libtool --tag=CXX --mode=link g++ -ftemplate-depth-50 -I../include -I../include/libtorrent -Os -pthread -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -g -O2 -L./ -lboost_system-gcc43-1_35 -lboost_filesystem-gcc43-1_35 -lboost_thread-gcc43-mt-1_35 -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -L/usr/lib -L/usr/lib -lssl -lcrypto -L/usr/lib -o simple_client simple_client.o ../src/libtorrent-rasterbar.la

Any ideas?

Adbot
ADBOT LOVES YOU

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

What would be the easiest way to print out a float that's constantly updating onto the terminal?

I just started writing in C++ and this is pretty much all I know how to do:

getProgress just returns a float value.

code:
while(tservice->unfinishedDownloads())
{
    std::cout << tservice->getProgress(1);
}
Thanks in advance :smith:

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Thanks for the prompt reply, that's exactly what I want to do.

I was afraid that I'd have to use another library but it's better than flooding my screen with 0.000 0.000 0.000 0.000 0.0001 eh?

Thanks again.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

That seems to have worked too. Thanks.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

ctz posted:

I believe the behaviour of a carriage return written to a terminal is standard according to POSIX.

And you can (must!) fix the brittleness by guaranteeing that `whatever' is of constant length. In particular, you'll get wrong output from use like:

code:
  cout << "\r" << float(1.234234) << flush;
  cout << "\r" << float(1.1) << flush;

How do I properly format floats or set them to a smaller precision?

Right now I'm just trying std::count.precision(3);

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm trying to compile a shared library that also happens to need a static library. How abouts would I do this?

This is what I ran to compile my SO.

code:
gcc -shared -Wl,-soname,libftorrent.so.1 -o libftorrent.so.1.0 ITorrentService.o TorrentService.o
The static library that those .o files needs is called libtorrent.a which also happesn to need Boost. Since it's a static library I assume I don't have to somehow include Boost as well?

I am so confused :smith:.

Please help.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Can someone tell me how to check if the input from std::cin is an integer or not?

I ended up using atoi but that doesn't seem right.

Thanks

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Anybody here know why I'm getting an assertion failure?

I was trying to make a linked list but when I removed something from the top of the list I get an error. That is if I have 3 items in the list, it'll crash after removing two. If I make it four items it works fine.

It compiles with no errors but it crashes when I run it. dequeue() seems to be the problem.

Here's what I have:

Customer is just an ADT with two fields in it.

code:
LinkList::LinkList()
{
	std::cout << "LinkList()" << std::endl;
	this->total = 0;
	this->front = NULL;
	this->back = NULL;
}

void LinkList::enqueue(Customer c)
{
	Node* person = new Node();
	person->client = c;
	person->next = NULL;

	if(this->back == NULL)
		this->front = person;
	else
		(this->back)->next = person;

	this->back = person;
	this->total++;
}

void LinkList::dequeue()
{
	if(this->back != NULL)
	{
		Node* temp = this->front;

		if(this->front == this->back)
		{
			this->front = NULL;
			this->back = NULL;
		}
		else
			this->front = (this->front)->next; // this is where i think the error is

		temp->next = NULL;

		delete temp;
		
		this->total = this->get_length() > 0 ? this->total - 1 : 0;
	}
}

LinkList::~LinkList()
{
	delete this->front;
	delete this->back;
	std::cout << "~LinkList()" << std::endl;
}
Header for that (important parts):
code:
class LinkList
{
	private:
		int total;
		Node* front;
		Node* back;
};
And node is just this:
code:
Node.h

class Node
{
	public:
		Node();
		~Node();
		Customer client;
		Node* next;
};
The constructor and destructor for Node is just empty.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Brecht posted:

I took your code and made it into a compilable program -- I had to define the get_length() method myself, typedef'd int as Customer, and removed Node's constructor and destructor as it didn't seem to need to do anything. That's at http://pastebin.org/80828 -- after making those changes I don't have any problems running the program, adding 3 customers, and removing them. So my guess is either your get_length() is different than mine and it's crashing there, or there's some other ancillary code causing you problems that you haven't listed.

However, few additional comments:
- you don't need to prepend this-> to access member variables
- your constructor should use initializer lists to initialize member vars rather than setting them explicitly in the constructor body
- Node seems to be a plain-old-data type, typically in C++ you define those as structs rather than classes
- the line you commented 'i think the error is here' could be made safer, as you're dereferencing 'front' without checking it's not null first. Without analyzing your logic too deeply, I bet it works OK in this instance by coincidence.
- you probably have a memory leak in the LinkList destructor -- you delete the front and back Nodes, but what about all the ones in between?

Thanks, I've read over your comments and gone through with the suggestions. I still don't know what was wrong with my program, I copied and pasted the methods from your pastebin and it still didn't work (assertion). I ended up rewriting everything and it worked :confused: in the end. What the hell.

RE: Memory leak, Something like this in the ~LinkList destructor should work, right?

while(front != NULL)
dequeue();

Acer Pilot fucked around with this message at 23:25 on Jan 23, 2010

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

He might find this useful: http://www.cplusplus.com/doc/tutorial/dynamic/

I think that site is listed in the OP too, helped me quite a bit when I started learning C++.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

If they're in a class you'd have two files:

myFunctions.h (your header file)
myFunctions.cpp (your definitions)

You would include myFunctions.h in main.cpp.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm trying to implement a binary search tree and can't, for the love of all things good, figure out what's wrong with my remove function.

Please help.

code:
Node* RBT::BST_remove(Customer c)
{
	Node* t = get_node(c);

	if(t != NULL)
	{
		Node* left = t->get_left();
		Node* right = t->get_right();

		if((left != empty) && (right != empty))
		{
			cout << "1" << endl;
			Node* pre = get_max(t->get_left());
			replace_node(t, pre);
		}
		else if((left != empty) || (right != empty))
		{
			cout << "2" << endl;
			if(left != empty)
				replace_node(t, left);
			else
				replace_node(t, right);
		}
		else
		{
			cout << "3" << endl;
			replace_node(t, empty);
		}
	}

	return t;
}

void RBT::replace_node(Node* o, Node* n)
{
	Node* parent = o->get_parent();

	if(o == parent->get_left())
		parent->set_left(n);
	else
		parent->set_right(n);

	if(n != empty)
		n->set_parent(parent);
}

Node* RBT::get_max(Node* n)
{
	Node* pos = n;

	while(pos->get_right() != empty)
		pos = pos->get_right();

	return pos;
}
empty is just an empty node (eg. new Node())

I also tried this:

code:
Node* RBT::BST_remove(Customer c)
{
	Node* t = get_node(c);
	//Node* left = *t->get_left();
	//Node* right = *t->get_right();
	Node* temp = t;

	/*if(t->get_left() == empty)
		*t = *t->get_left();
	else if(t->get_right() == empty)
		*t = *t->get_right();
	else if((t->get_left() != empty) && (t->get_right() != empty))
	{
		Node* node = new Node(t->get_customer(), t->get_parent(), 
t->get_colour(), t->get_left(), t->get_right());
		*t = *node;
	}*/

	return temp;
}
...which just causes a runtime error.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Paniolo posted:

Right off the bat I notice you're passing the Customer object by value instead of pointer or reference, which is almost definitely wrong for what you're trying to do. But whether that's the cause of the problem you're having or just another problem waiting to happen is impossible to know because you haven't really specified what your problem is. "It's not working" is not very helpful.

The second function is probably crashing because get_node() is returning a null pointer, which you aren't checking for. Hard to be more helpful since there's no source for get_node() or the Node class.

Also, learn to use your debugger, it really should be the first thing you go to when you're having a problem like this. Step through the offending function line by line and look for the exact moment the actual effect of the code diverges from your reasoning about what it should do.

Sorry, forgot about get_node() :(. The problem with my first function is that it seems to delete two nodes (it prints out 2 twice) before it just gives me a runtime error without a prompt to run my VS2008 debugger. Still pretty new to using VS so not sure how to force it to open the debugger...

Related question, should parameters for functions that return pointers always be pointers as well?

code:
Node* RBT::get_node(Customer c)
{
	Node* pos = root;	// current position;

	while(pos != empty)
	{
		if(c < pos->get_customer())
			pos = pos->get_left();
		else if(c == pos->get_customer())
			return pos;
		else
			pos = pos->get_right();
	}

	return NULL;
}
edit: THanks for replying at 3AM in the morning.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Okay, I solved the remove problem! I forgot to account for children on some occasions...

When should my Customer objects be Customer* and when should they be Customer* &variable?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Shouldn't it be something like this?

code:
using namespace std; // too lazy to type out std::

ostream& operator<<(std::ostream& os, const my_class& obj)
{
	os << your class' to_string stuff here probably << ends;
	return os;
}

cout << obj;
edit: I can't spell :(

Acer Pilot fucked around with this message at 11:24 on Apr 17, 2010

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

pseudorandom name posted:

pipe(7)

I'm not sure what exactly you're doing, but guessing as to what you're assignment actually is instead of what you've described, I'd say you only need two pipes (one for orders to the threads, one for replies from the threads to the master thread).

I think I'm in the same class as that guy lol.

So far I've been able to get it to do this:
code:
 creating process 2315 - 0
 creating process 2319 - 1
Seats available: 36
 creating process 2318 - 1
Seats available: 36
 creating process 2320 - 1
Seats available: 36
 creating process 2321 - 1
Seats available: 36
 creating process 2317 - 1
Seats available: 36
 creating process 2316 - 1
read: 36
Seats available: 36
read: 36
read: 36
read: 36
read: 36
read: 36
0: 36
1: 36
2: 36
3: 36
4: 36
5: 36
Can someone here give an example of how to use, I'm assuming, READ/WRITE to act as a mutex for a shared variable?

edit:

My function for the forks looks like this:

code:
        close(fd[child_idx][0]);
        char buf[BUFSIZE];
        
        int seats_open = seats_available; // originally *seats_open = &seats_available
        seats_open--; // originally *seats_open = *seats_open - 1;
        snprintf(buf, BUFSIZE, "%ld", (long int)seats_open);
        
        if(sizeof(buf) != write(fd[child_idx][1], buf, sizeof(buf)))
            exit(-3);
            
        std::cout << "Seats available: " << buf << std::endl;
        close(fd[child_idx][1]);
It doesn't seem to be updating the value of seats_available

Acer Pilot fucked around with this message at 15:53 on Oct 19, 2010

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

roomforthetuna posted:

Where do you expect it to update that value? It copies it into "seats_open" and then only updates seats_open.

The "originally" method in the comments is closer to actually updating the value.

I changed it back to how it was originally now but it still only seems to deduct it from seats_available once... Any ideas on what I did wrong?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

roomforthetuna posted:

Though even if it was working as you'd expect, you'd still need some sort of locking anyway, or you risk all 6 processes first reducing the number, then the same reduced number (30) being piped 6 times.


This is exactly what's happening now, all 6 processes are reducing the number 6 times. Yikes!

Thanks, I'll look through the memory locations and that link.

I already did it via POSIX threads but our prof also wanted us to try it out with pipes or sockets. The pthreads seemed pretty easy but I'd never worked with pipes before :(.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Anyone have any experience getting QT running with Visual Studio 2010? I can only compile release but not debug.

Was thinking about compiling QT from source but I don't think I have the hours it could take to compile.

Solutions or alternatives?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Having some trouble with converting something to float which also happens to be a pointer.

Note: projectTestFace is a float* and I'm using OpenCV2.2 for the Matrices.

The original:
code:
CvMat *m_projectedTrainFaceMat;
float d_i;
i = 0;
d_i = projectTestFace[i] - m_projectedTrainFaceMat->data.fl[iTrain * m_nEigens + i];
The new version:
code:
Mat *m_projectedTrainFaceMat;
float d_i;
i = 0;
d_i = projectTestFace[i] - m_projectedTrainFaceMat->data[iTrain * m_nEigens + i];
What should I be doing to get m_projectedTrainFaceMat->data[iTrain * m_nEigens + i] to return as a proper float.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm thinking about using Boost regex to iterate through a queue. I don't know how long the queue will be, could be thousands of entries, and there could be a dynamic number of regexes I'll use. Are there any tradeoffs or better solutions for this?

Specifically, the queue will be a long list of URLs and I want to search for specific types of URL.

I'm also open to suggestions on what the best type of list/array is best to use for such a list. Should I roll my own?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Paniolo posted:

You should almost never roll your own basic data structure. Certainly never before you've implemented it with a STL vector or list, profiled it, and identified specific characteristics which are causing performance issues.

You haven't given much information on exactly what you're trying to do. A regex is a heavyweight solution but is pretty straightforward to implement and unless you know for a fact that this is a bottleneck you should go with whatever is easiest to implement.

On the other hand, if you need to categorize URLs by paths which share common base components then you could look into using a trie. For example, each slash-delimited component of the URL could be a node in the trie. This would work pretty well for categorizing URLs in most situations.

Thanks for the advice, going to try out using a trie instead of using regex, it looks really versatile. I'll use a list as well to store the actual URLs since I think I'll just be going FIFO.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Paniolo suggested, a few posts up, that I should use a trie. Anyone have any suggestions for a good C++ implementation or library for trie? Preferably one that compiles in GNU.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Brecht posted:

gcc ships with a GNU implementation of a trie.

http://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds

Thanks, I saw that one and am trying out.

Another question, what's the MySQL C++ connector of choice around here? I was looking at libmysqlcppconn but the documentation is a little iffy.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Dicky B posted:

Effective C++.

This is a good book.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I have a Boost multithreading question.

code:
void consumer()
{   
    while(this->is_running)
    {
        boost::lock_guard<boost::mutex> lock(this->queue_lock);

        if(this->queue.size() >= 10)
        {   
            // do stuff
        }

        this->cond.notify_all();
        this->cond.wait(this->queue_lock);
    }
}

void producer()
{
    while(this->is_running)
    {
        boost::lock_guard<boost::mutex> lock(this->queue_lock);

        // pop object from shared vector
        // do stuff to the object
        // add object to this->queue

        this->queue_lock.unlock();
        this->cond.notify_all();
        // wait for 10-15 seconds
    }
}
edit: this->queue_lock is a boost::mutex.

Right now, I'm thinking there will be 4 producers and one consumer running. Will any of my threads starve if I use Boost mutexes like this? Something doesn't seem right with producer(). Do I need to use a shared_mutex and upgrade locks?

Also should I use unique_lock instead or stick with lock_guard?

Acer Pilot fucked around with this message at 02:27 on May 4, 2012

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

nielsm posted:

If that's what you are actually doing (pushing items into a queue in a producer and consuming them in a bunch of worker threads) then I would suggest looking into using a lock-free queue implementation instead. Your code will be cleaner and likely also faster.

Ah, sorry, I was editing my post when I saw yours come up.

The producer pops an object from a shared vector, does something to it, then pushes it to a queue. I think that will probably mean it needs a lock. I'm worried that not all 4 of the producers will have access to the shared vector though.

e: Can I still do this with a lock-free queue?

Acer Pilot fucked around with this message at 02:33 on May 4, 2012

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Thanks for replying again nielsm.

A vector named data is shared between the 4 producers. Each producer pops an object from the data vector, processes it, and then adds the processed object to another shared vector named queue. When the consumer sees that there are 10 items in the queue vector, it processes the contents and empties the queue vector.

Now that I write this, I see that I'll probably need another mutex for the data vector. Thanks to your explanation I just realized that I only need to lock a producer when it pops from the data vector. Can starvation still occur though?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Thanks a lot nielsm and roomforthetuna! Time to rewrite this junk.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

What's an easy way to generate an md5 or sha-1 hash of a string? OpenSSL?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Isilkor posted:

If you already use OpenSSL in your application, then you should probably just use that. If you don't, get some smaller implementation that doesn't pull in hundreds of kilobytes of code, plus a bad license. If you just want SHA-1, boost.uuid has an implementation that's licensed very permissively; look at <boost/uuid/sha1.hpp> but take notice that it isn't part of the public interface (copy it to your own file and namespace if you want to use it).

Nota bene: MD5 is considered cryptographically broken by CERT and you shouldn't use it in new code. SHA-1 has some mathematical weaknesses and while not entirely broken yet, if you want to be on the safe(r) side, use a function from the SHA-2 set (for example, SHA-256). (Disclaimer: A reduced rounds version of SHA-2 has been shown to be susceptible to attack, but it hasn't yet been extended to the full SHA-2 algorithm.)

Thanks for the reply. I'm not using it for any security purposes, just trying to figure out an "easy" way to generate a fixed length hash to use for look ups in a database. Do you guys happen to have any alternative ideas to accomplish this?

e: Not using OpenSSL in the program but open to it. Using Boost already though.

Acer Pilot fucked around with this message at 03:07 on May 20, 2012

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm trying to generate a fixed length hash (that won't likely have collisions) for a value like this:

product[max integer of length 10]model[max integer of length 10]price[a float or double of unknown length]

I was under the impression that using MD5, SHA1, or SHA256 would be an easy way to generate this but I'd love a more efficient/correct way.

Please take note that I might need to be able to generate the hash again in a PHP script.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Suspicious Dish posted:

You do know what SQL is, right?

Yes, I'm doing it to group multiple indexes into a hash rather than doing a large set of subqueries.. We're using a WHERE IN and need a way to look up multiple indexes for a large set of values in a single query.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Suspicious Dish posted:

And you thought you needed a hash? A cryptographic hash, even? This is an example of the XY problem in action, here. The database will hash values for you. You don't need to. Create a single easily generated value, and use that.

Ahh, ok. Thanks everyone.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm trying to write a daemon in C++ and I think I want it to have child processes. The child processes will all be from the same class but have different data. I plan on having them communicate to each other with pipes or through Boost's IPC so they know when they're supposed to terminate.

The question is, where exactly do I spawn the child processes and how? Do I do it in the main loop in the parent process?

Here's the code I'm starting off with:

code:
int main(int argc, char *argv[])
{	
	pid_t pid, sid;
	
	pid = fork();
	if(pid < 0)
	{
		exit(EXIT_FAILURE);
	}

	if(pid > 0)
	{
		exit(EXIT_SUCCESS);
	}

	umask(0);
		
	sid = setsid();
	if(sid < 0)
	{
		/* Log the failure */
		exit(EXIT_FAILURE);
	}
	
	if((chdir("/")) < 0)
	{
		/* Log the failure */
		exit(EXIT_FAILURE);
	}
	
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
	
	while(true)
	{
		// have we spawned children?
		// if not, spawn the children
		sleep(30);
	}

	exit(EXIT_SUCCESS);
}

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Gazpacho posted:

fork() is precisely what spawns the child process. By the time fork() returns, it's all set up. The parent process will return from fork with a positive number and the child will return with 0. From there on you have two processes executing the same code. The return value from fork allows them to take different paths through that code.

If your parent process is a daemon then it doesn't make sense to call exit when pid > 0 because that will immediately terminate the parent.

Sorry if these are things you already know, I'm just confused that you're calling fork and then your code comment suggests that there isn't already a child process at that point.

Thanks for your answer, I thought the code where we check if the pid > 0 was so we could let the system take control of the process and run it as a service in the background. Did I assume incorrectly??

And I guess the better question is, how do I let the daemon create additional processes?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Crankit posted:

How does CodeBlocks compare to NetBeans / Eclipse and vice-versa?
I've used the MS tools and I've used CodeBlocks on a linux machine very briefly but I've not used NetBeans or Eclipse.

Well I like CodeBlocks over Eclipse. NetBeans can make proper Makefiles though if you're lazy, CodeBlocks needs a plugin to do so.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

What's a good library for thread-safe logging to a text file?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Good ideas, thanks.

Now I need to figure out a good way to buffer the messages with little to no blocking.

Adbot
ADBOT LOVES YOU

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

So what's a good way to check if one or more threads have completed their task?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply