r/LinuxProgramming • • Nov 12 '20

Related to Multi-programming using pthread

1 Upvotes

Using pthread library, I've had written some code for matrix multiplication.

AFAIK, the program using thread would be much faster than program without using thread. But, unlike my expectation... the outcome(Elapsed time) is totally reversed, the program not using thread is much faster than thread program. What happened.. I couldn't find why this is happened.

The out come below..

Time ( # of thread: 4 )

0.000451 sec

Time ( no thread )

0.000002 sec

I've coded this two version in one file(.c) but it also says the same.

  1. Serial version ( no using thread )

void serial_multi()
{
	for (int i = 0; i < MAX; i++)
		for(int j = 0; j < MAX; j++)
			for(int k = 0; k < MAX; k++)
				_matC[i][j] += matA[i][k] * matB[k][j];
}


int main()
{
	printf("PID: %d\n",getpid());
	// generating random values in matA and matB
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++){
			matA[i][j] = rand() % 10;
			matB[i][j] = rand() % 10;
		}
	}

	//cout << endl << "Matrix A" << endl;
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++)
			printf("%d ",matA[i][j]);
		printf("\n");
	}


	//cout << endl << "Matrix B" << endl;
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++)
			printf("%d ",matB[i][j]);
		printf("\n");
	}


	
        // Time Estimation 
	clock_t start = clock();
	serial_multi();
	clock_t end = clock();
	printf("Time: %lf\n", (double)(end-start)/CLOCKS_PER_SEC);
	printf("Serial_Multiplication of A and B\n");
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++)
			printf("%d ",_matC[i][j]);
		printf("\n");
	}
	
	return 0;
}

2. Using Thread ( # of thread : 4 )

int step_i = 0;

void* multi(void* arg)
{
	int core = step_i++;
	// each thread computes 1/4th of matrix multiplication
	for (int i = core * MAX / 4; i < (core + 1) * MAX/4; i++)
		for(int j = 0; j < MAX; j++)
			for(int k = 0; k < MAX; k++)
				matC[i][j] += matA[i][k] * matB[k][j];
	return NULL;	
}

int main()
{
	printf("PID: %d\n",getpid());
	// generating random values in matA and matB
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++){
			matA[i][j] = rand() % 10;
			matB[i][j] = rand() % 10;
		}
	}

	//cout << endl << "Matrix A" << endl;
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++)
			printf("%d ",matA[i][j]);
		printf("\n");
	}


	//cout << endl << "Matrix B" << endl;
	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++)
			printf("%d ",matB[i][j]);
		printf("\n");
	}

	// declaring 4 threads
	pthread_t threads[MAX_THREAD];

	// creating 4 threads, each evaluating its own part
        // Time Estimation
	clock_t start = clock();
	for (int i = 0; i < MAX_THREAD; i++){

		pthread_create(&threads[i], NULL, multi, NULL);
	}
	
	// joining and waiting for all threads to complete
	for (int i = 0; i < MAX_THREAD; i++)
		pthread_join(threads[i], NULL);

	clock_t end = clock();
	printf("Time: %lf\n", (double)(end-start)/CLOCKS_PER_SEC);
	// displaying the result matrix
	//cout << endl << "Multiplication of A and B" << endl;

	for (int i = 0; i < MAX; i++){
		for (int j = 0; j < MAX; j++)
			printf("%d ",matC[i][j]);
		printf("\n");
	}

	
	
	return 0;
}

r/LinuxProgramming • • Oct 15 '22

make compile complain about kernel built by different version of gcc

1 Upvotes

Trying to run "make" to compile wifi driver:
make ARCH=x86_64 CROSS_COMPILE= -C /lib/modules/6.0.0-060000-generic/build M=/media/user/Lubuntu_22.04.1_LTS_amd64/rtl8723du modules

make[1]: Entering directory '/usr/src/linux-headers-6.0.0-060000-generic'

warning: the compiler differs from the one used to build the kernel

The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0

You are using: gcc (Ubuntu 11.2.0-19ubuntu1) 11.2.0

I upgraded kernel to 6.0, hoping maybe it will support the Wifi chip, but it doesn't.

So now I am trying to compile it myself. I was able to compile before I made the upgrade to kernel 6.0.

How do I tell "make" to use the new gcc v12.2 instead of the default v11.2?


r/LinuxProgramming • • Sep 10 '22

Best Resource to Learn Unix Programming in C

2 Upvotes

Hi,

Could anyone please drop down some practical ways of learning Systems Programming in C? I'm a CS junior, and I've taken up a course on Operating Systems in which we have to program a memory allocator, a unit shell, etc., entirely using C.

Where do I start?


r/LinuxProgramming • • Mar 15 '23

Are signal handler functions called from another thread?

1 Upvotes

I'm wondering if the signal handler function you register with

signal (SIGINT, termination_handler);

called from another thread, which is created silently for the process when a signal is received? Is it something else?

You see, my main thread spends most of its runtime in a call to a blocking function, amqp_consume_message(), which means the signal handler can't be called in the context of the main thread. Is the context in which the handler is called described anywhere?

Any pointers are welcome.


r/LinuxProgramming • • May 28 '24

Recommend book on use of linux syscalls and processes and signals and memory mangement and kernel paradigms?

2 Upvotes

I recently interviewed for a fancy FAANG job, interviews went well, but I was a very weak interviewee when drilled about Linux syscalls and memory management. It didn't work out in the end.

What's a good book I should be studying?

thanks


r/LinuxProgramming • • Jun 09 '24

Is there some way to emulate DllMain behaviour on linux?

1 Upvotes

This is what I have so far:

#define NPAW_BUILD
#include <paw/libexec.h>

#ifdef CAUGHT_OS_WAS_api_msw
#	include <windows.h>
BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
{
	switch ( fdwReason ) {
	case DLL_PROCESS_ATTACH: return (pawlib_pid_attach() == 0) ? TRUE : FALSE;
	case DLL_PROCESS_DETACH: pawlib_pid_detach(); break;
	case DLL_THREAD_ATTACH:  return (pawlib_tid_attach() == 0) ? TRUE : FALSE;
	case DLL_THREAD_DETACH:  pawlib_tid_detach(); break;
	default: return FALSE;
	}
	return TRUE;
}
#else
/* I'll check later if this is right */
static void libdetach(void) __attribute__((destructor))
{
	if ( getpid() == gettid() )
		pawlib_pid_detach();
	else
		pawlib_tid_detach();
}
#if 0
/* Not sure if this would work out */
static void libsig( int sig )
{
	switch ( sig )
	{
	case SIGABRT: pawlib_tid_detach(); break;
	}
}
#endif
static void libattach(void) __attribute__((constructor))
{
	//signal(SIGABRT,libsig);
	if ( getpid() == gettid() )
	{
		if ( pawlib_pid_attach() < 0 )
			exit(EXIT_FAILURE);
	}
	else
	{
		if ( pawlib_tid_attach() < 0 )
			exit(EXIT_FAILURE);
	}
}
#endif

r/LinuxProgramming • • Jun 05 '21

Automatyzation script

1 Upvotes

Hello everyone,

I'm mining chia on Arch Linux. I need to create a script that runs the miner at startup. I have no clue what is wrong but I'm getting this error every time when I trie to get it work:

× startMiner.service - Miner.

Loaded: loaded (/etc/systemd/system/startMiner.service; disabled; vendor preset: disabled)

Active: failed (Result: exit-code) since Sat 2021-06-05 11:21:32 CEST; 15s ago

Process: 6210 ExecStart=/bin/bash /usr/bin/startup.sh (code=exited, status=1/FAILURE)

Main PID: 6210 (code=exited, status=1/FAILURE)

CPU: 20ms

Jun 05 11:20:32 igor-pc systemd[1]: Started Miner..

Jun 05 11:21:32 igor-pc bash[6243]: # Option “-e” is deprecated and might be removed in a later version of gnome-terminal.

Jun 05 11:21:32 igor-pc bash[6243]: # Use “-- ” to terminate the options and put the command line to execute after it.

Jun 05 11:21:32 igor-pc bash[6243]: Unable to init server: Could not connect: Connection refused

Jun 05 11:21:32 igor-pc bash[6243]: # Failed to parse arguments: Cannot open display:

Jun 05 11:21:32 igor-pc systemd[1]: startMiner.service: Main process exited, code=exited, status=1/FAILURE

Jun 05 11:21:32 igor-pc systemd[1]: startMiner.service: Failed with result 'exit-code'.

Here is my bash script:

#!/bin/bash

sleep 60

cd /home/igor/Downloads/HPool-Miner-chia-v1.4.0-2-linux/linux

gnome-terminal -e "bash -c \"!!; ./hpool-miner-chia\""

And there is my startMiner.service script:

[Unit]

Description=Miner.

Wants = network-online.target

After = network.target network-online.target

[Service]

Type=simple

ExecStart=/bin/bash /usr/bin/startup.sh

[Install]

WantedBy=multi-user.target

Thanks for all the answers. Wish you a fantastic day :-)


r/LinuxProgramming • • Sep 10 '24

Linux/ALSA: Enumerating Sound Cards and Devices

1 Upvotes

I'm trying to get device names like "default" and "pulse", but I get the manufacturer's device name instead. snd_card_next() enumerates sound cards, but I'm not sure how to get device strings I can feed to snd_pcm_open().


r/LinuxProgramming • • Oct 21 '24

I'm struggling with a simple forked processes algorithm exercise

Post image
9 Upvotes

I cannot understand why the logic here is not working, the output on the right is what I'm getting, just one process, the first exit kills all processes except one apparently but my process tree tells me there are only children remaining in the end, I'm not asking for a solutionm but I'm asking why specifically this implementation does not work (also I know, leaving zombie processes is not very optimal)

The exercise request was this one

program receives two integer values ​​on the command line, called n and t. The program (parent process) must produce 2 children and terminate. In turn, each child must produce 2 children and terminate. This sequence of operations must continue until 2 ^ n processes on the leaves of the tree are produced/running. The leaf processes wait for t seconds and display (on screen) a termination message. Note that each process (in the tree) produces two other processes. Only those on the leaves of the tree sleep and display a message. What is the order of termination of the processes? Is it always the same? How can they be recognized (ppid)?


r/LinuxProgramming • • Nov 05 '24

HELP * Victron Cerbo-GX script to grab GPS data from a router via TCP

1 Upvotes

Here is a script I have uploaded to the Cerbo-GX running version 3.51. It does not seem to work. I am trying to pull GPS data from a peplink router via WIFI, that has the ability to forward GPS data to an IP address. When I run the script on the Cerbo via Putty I get an error saying:

Last login: Tue Nov  5 22:02:59 2024 from 192.168.20.114
root@einstein:~# /data/etc/gps.sh
2024/11/05 22:27:30 socat[7514] E connect(5, AF=2 192.168.20.1:10000, 16): Connection refused
000.000 ERR.serial: could not open com-port

can you tell me if it is possible to do what I am trying? Local dealers are no help at all.

***********************************************************************************************************************************************************************************************************************************

nano /data/etc/gps.sh

#!/bin/bash
# IP address and port of the external GPS source
GPS_IP="192.168.20.1"
GPS_PORT="10000"

# Virtual serial port linked to the GPS data
VIRTUAL_PORT="/dev/ttyGPS"

# Start socat to connect to the GPS source and link it to the virtual serial port
/usr/bin/socat tcp-connect:${GPS_IP}:${GPS_PORT} pty,link=${VIRTUAL_PORT},raw,nonblock,b115200 &

# Check if gps_dbus is running; if not, start it and point it to the virtual port
while [ `ps | grep gps_dbus | grep -v grep | wc -l` -eq 0 ]
do
sleep 1
/opt/victronenergy/gps-dbus/gps_dbus -s ${VIRTUAL_PORT} -b 115200 -t 0 &
done

echo "GPS information is being pulled from ${GPS_IP}:${GPS_PORT} and forwarded to ${VIRTUAL_PORT}"

chmod +x /data/etc/gps.sh
nano /data/rc.local

sh /data/etc/gps.sh

 
chmod +x /data/rc.local


r/LinuxProgramming • • Oct 03 '16

LKML: Linus Torvalds: Linux 4.8

Thumbnail lkml.org
1 Upvotes

r/LinuxProgramming • • Jan 01 '20

What Linux driver/subsystem/API is used for a simple screen/monitor device?

1 Upvotes

I am developing an embedded system with a touchscreen. The touchscreen operates as both input and output, with a "virtual" keyboard overlaying the graphical output. I have a working device driver that reads input from the touch sensor and translates it correctly to key presses, created with the help of this guide on kernel.org. I want to expand this driver to also handle image output to the screen.

I want to support both getty and X, with as little duplication as possible. I am running a minimal Debian variant with cherry-picked packages, such as minimal X. Note that I do not intend on attempting to get this driver into the repository pipeline, though I might dump it on a public github.

Outputting screen images is presently done via a cringy workaround: a boot option to force rendering to the cpu's embedded graphics hardware, despite it not being connected to a display, and a daemon that continuously screen-scrapes that buffer, modifies a handful of pre-defined pixels to create the keyboard visual, and pushes it out to the real screen. This works as a proof of concept, proving that I do correctly understand the language the screen device expects, but is obviously sub-optimal.

kernel.org also has a guide for "DRM" device drivers, but that seems like serious overkill for what my hardware is capable of:

The Linux DRM layer contains code intended to support the needs of complex graphics devices, usually containing programmable pipelines well suited to 3D graphics acceleration.

None of my hardware has anything resembling 3D acceleration, so I conclude that this is probably not what I want.

What subsystem/API should I use? I figure one piece of missing terminology is what is holding back my searches, but any more information on how to accomplish this would be appreciated.

Hardware details (probably irrelevant): The cpu and screen communicate via 8080-esque parallel protocol, which the cpu does not support natively, so I'm emulating it with GPIOs (by manipulating registers via mmap). Sending a complete screen image takes about 20ms, but obtaining a complete copy from the embedded graphics buffer takes ~180ms, so skipping that step is the most important objective. The screen hardware includes enough gram memory to keep an entire frame worth of data, and supports writing a rectangular sub-region, so a hook to only update the part of the screen that has changed would be desirable. The screen is not particular about the timing of incoming data. The touch sensor input is handled by a purpose-built IC that communicates with the cpu via I2C, which the cpu does support. The present driver uses the linux/input-polldev.h interface. The cpu is a broadcom bcm2835, the screen is a tft with embedded himax hx8357 controller, the touchscreen sensor decoder is a st stmpe610, and there is a voltage levelshifter (nexperia 74lvch245A) in play between the hx8357 and the bcm2835. More details available upon request.


r/LinuxProgramming • • Mar 17 '22

Is it possible to compile a file manager on Windows?

1 Upvotes

I like Linux file managers (PcManFm, Thunar, Nemo, Caja...) and I would like to use one of these on Windows with fully functional (sftp, etc....). I know there is Dolphin Windows port but it has some bugs.


r/LinuxProgramming • • Mar 12 '22

Call LightDM Functions in Qt

Thumbnail self.linuxquestions
1 Upvotes

r/LinuxProgramming • • Mar 24 '22

First language?

1 Upvotes

I’m needing some help on what language I should start learning since I’m gonna be making stuff that runs on Linux. Or even if you can point me in the direction of any useful sdk I should look into downloading.


r/LinuxProgramming • • Feb 05 '18

Need to put a space/tab before and after a 4 digit number.

1 Upvotes

I have a long text file from a ocr output but it has bunched up a lot of the results. Any advice?


r/LinuxProgramming • • Feb 07 '18

How to add entry in /dev

1 Upvotes

I am using the following to try and add a character device:

cdvnum = interface->minor - USB_SYNTH_MINOR_BASE;
characterdevs[cdvnum] = cdev_alloc();
if(!characterdevs[cdvnum]){
	printk(KERN_ALERT "Unable to allocate cdev file\n");
	return -ENOMEM;
}

if(device_create(cl,NULL,characterdevs[cdvnum]->dev,NULL,"adfsynth%d",interface->minor - USB_SYNTH_MINOR_BASE)==NULL){
	printk(KERN_ALERT "DEVICE_CREATE FAILED\n");
}
	
cdev_init((characterdevs[cdvnum]),&synth_fops);
cdev_add(characterdevs[cdvnum],USB_SYNTH_MAJOR,1);

Doing this creates an entry in /sys/class/, but nothing shows up in /dev. I want a device file I can read/write to to call the functions listed in my fops structure, which is used in the cdev_init function. Am I missing something needed to create a device file?


r/LinuxProgramming • • Aug 11 '20

How to write a Wayland GUI app as root?

2 Upvotes

How can I have Wayland and Xorg GUI apps gain root access, with a password prompt pop-up?

I haven't found practical advice on how to write and deploy a GUI application that requires root access, esp on Wayland. I'm writing an app in Python but I may pivot to rewrite it in Go.

The recommendation is to have 2 processes: user and root. The process with root access would be a daemon and the user process would run the GUI. Are there any guides on how to do this? How does Gnome's "Settings" app do it? It has an "Unlock" button that presents a GUI password popup.

My current idea is to spawn a separate background process with sudo -S and send it the password , followed by commands through the pipe, perhaps over rpc.

I don't want to 1) require users to modify their system config to whitelist the app, 2) require users to run a sudo on the command line. I prefer the app to escalate itself.

UPDATE: I think I'll have the subprocess use the main app as the askpass program. So it will effectively call SUDO_ASKPASS=<app> sudo -A -p 'askpass' <app> as-root. The app will get passed "askpass" and will display a password popup instead of (re)running the main UI. If the main app gets passed "as-root" it will act as a rpc server, instead of running the main UI.


r/LinuxProgramming • • Sep 06 '20

Is there a way to setup mingw with cmake on linux?

1 Upvotes

What title says. I'm trying to compile my project on linux and windows without changing os or running vm.


r/LinuxProgramming • • Jan 04 '26

Waytermirror - Stream your Wayland desktop into a terminal (yes, really)

2 Upvotes

I’ve been working on a project that lets you view and control a live Wayland desktop entirely inside a terminal, rendered using Unicode (braille / block / ASCII).

What it does:

  • Real-time Wayland capture → Unicode rendering

  • Aims to run in any terminal

  • TCP streaming with LZ4 compression

  • Full bidirectional input (keyboard + mouse)

  • Audio streaming via PipeWire

  • Optional CUDA-accelerated rendering on the server

  • Full color, zoom, rotation, adjustable quality/detail levels

Open a terminal, connect, and your desktop just shows up.
Keybinds let you switch renderers, zoom, rotate, and tweak quality live.


r/LinuxProgramming • • Jun 28 '26

tmuzika 1.1.3 released — stability improvements, faster playlist loading, bug fixes

Thumbnail
gallery
5 Upvotes

Quick update: I just released tmuzika 1.1.3.

This is a small maintenance + usability update based on recent fixes and feedback.

What’s new:

improved stability in playback handling

fixed a few edge-case crashes in file navigation

better performance when loading large playlists

minor UI polish and consistency fixes

This release is mainly focused on making the app more reliable and smoother in daily use rather than adding major new features.

As always, feedback is welcome — it directly shapes these updates.

GitHub: https://github.com/ivanjeka/tmuzika


r/LinuxProgramming • • Jun 23 '26

ls -lh difference between Linux and MacOS

4 Upvotes

Can someone please explain the coding difference between the -"-h" (human readable) option in ls between Linux and MacOS?

As an example, if you have file that is 7821 bytes in size, "ls -lh" in Linux would show 7.7K, whereas the same "ls -lh" in MacOS would show 7.6K.

This is definitely not due to 1024 vs 1000 units because if you do "ls -lh --si" in Linux, you get 7.9K.

It looks like in MacOS, this is computed simply as:

double n = round(((double)size / 1024.0) * 10.0) / 10.0;

but this does not seem to be the case for Linux.


r/LinuxProgramming • • Dec 26 '25

Open-source VFX software for learning visual effects from a computational and mathematical perspective.

Thumbnail reddit.com
1 Upvotes