I want to create a process runni开发者_C百科ng under linux that creates multiple threads, each thread writing their own data out to a receiving process over a UDP socket connection. For sizing, say I need to have up to one hundred of these threads all running simultaneously with threads coming and going.
Is it better to have each thread open up it's own socket to the same destination using the same UDP port number when the thread is created (thus needing 100 separate file descriptors) or to open the socket one time in the main thread and pass that file descriptor to each of the threads so it each uses the same socket? Each thread will be generating about 20 packets per second, each packet roughly 800 bytes in length. There is no synchronization between threads.
I don't think there would be a speed benefit with using multiple sockets unless possibly on a multihomed machine. The physical network layer cannot simultaneously send two packets at once. I would be a little concerned, though, about using a single socket without synchronization. I think it is supposed to be thread-safe, but some googling seems to indicate potential problems. I would probably put a sync around it if I were coding it because the underlying placement of the packet on the wire is going to ultimately be serialized.
Individual socket writes are synchronized for you (at the socket level), and assuming you don't have any grouping or relative ordering dependencies, this will work fine.
I would go for a loose-coupling
approach - have all threads independent. The load doesn't seem excessive so loose-coupling appears appropriate.
Of course, some folks will disagree but from a systems point-of-view, loose-coupling is always preferable ... where applicable :-)
your solution work properly because you don't have same data to share between threads. But I think you can use connection pool ( make some connection and borrow to threads ) and threads in queue wait for give connection from pool.if the number of connection and thread are big performance lose[network restriction and your machine restriction] other solution that queue all thing is don't use pooling and queue all thing.but I think pooling give better performance.
精彩评论